Search code examples
javajpaquerydsl

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 ?


Solution

  • This won't do?

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