简体   繁体   中英

JPA : field with @ManyToMany and @ManyToOne

Is it possible in JPA that a field of an entity have both the annotations @ManyToMany and @ManyToOne ?

This is my tables :

Table1
   - String id (pk)
   - ...

Table2
   - ...
   - String object_id (fk Table1.id)

Table3
   - ...
   - String object_id (fk Table1.id)

And this is my entities (simplified ofc) :

Entity1 {
    private Entity1PrimaryKey pk;
}

Entity2 {
    private Entity1 entity1;
}

Entity3 {
    private Entity1 entity1;
}

I'll do my best to explain :

  • @ManyToOne : Entity2 and Entity3 have both a field that refers to Entity1. So there's a many to one relation.

  • @ManyToMany : in a JPA Query, I need to join Entity2 and Entity3. This is the query in SQL :

    SELECT fieldFromTable2, fieldFromTable3 FROM Table2 INNER JOIN Table3 ON Table2.object_id = Table3.object_id;

    So with this, I thought I had to use @ManyToMany. But I'm getting some errors.

So I would like to know : is this possible to put @ManyToMany and @ManyToOne on the same field of an entity ?

This won't do?

SELECT t2.fieldFromTable2, t3.fieldFromTable3
FROM Table2 t2, Table3 t3
WHERE t2.entity1 = t3.entity1;

The short answer: No, I do not believe a single field can have multiple relationship annotations applied to it. This seems implied since conceptually a relationship is between two Entites.

To dig further into your question, I think you're misunderstanding the use of collection based relationships (@OneToMany, @ManyToMany). These occur when an entity is related to multiple instances of another entity, ie a row in table1 can be joined to multiple rows in table2. If table1 also relates to table3, that is a completely separate relationship.

A OneToMany example is a student can send many emails, but each specific email can only be sent by a single student.

A ManyToMany example is each college course has many students and every student takes multiple courses.

If we also wanted to know which books a student requires for all of their courses, that would be derived separately from the other relationships.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM