Search code examples
javadatabasejpaentity-relationshipmodeling

Create a (Many to Many) Many relationship using JPA and Java EE


I am trying to create a relationship using JPA. It is confusing and i can't wrap my head around it. It's weird because i think that JPA limits this.

Here's the idea:

A relationship...

TableA
   pk    idA

between...

TableB
   pk    idB

forms a table:

TableA_TableB
   pfk   idA
   pfk   idB

And relate TableA_TableB (or the table that was generated) with another table, TableC:

TableC
   pk    idC

forms the table:

TableA_TableB_TableC
   pfk   idA
   pfk   idB
   pfk   idC

and i want to add an attribute to table TableA_TableB_TableC called value. So it'll be like this:

TableA_TableB_TableC
   pfk   idA
   pfk   idB
   pfk   idC
         attribute

However, the annotation @ManyToMany() is rather limiting. I can only join a table with 1 key with another.

I also can't find some decent examples online. So yeah.

Thanks in advance.


Solution

  • The ManyToMany-Annotation is meant for "plain" relationships, without any additional information.

    I would recommend to do it like this:

    • Create a new Persistent Entity Class (i.e. "TableABCRelationship")
    • Link all three existing entity classes to the new entity class, using three OneToMany-Annotations at the existing classes and three ManyToOne-Annotations in your new class
    • Add the additional field "attribute" in your new entity class
    • Change all existing references

    Depending on your existing code, it might be some effort to refactor everything...