1

I am new in Hibernate and after reading documentation, I get confused about the proper usage for @ManyToMany relationship.

Here is the bi-directional example:

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "person_address",
        joinColumns = @JoinColumn(name = "person_id"
            /*referencedColumnName = "id", nullable = false, updatable = false*/),
        inverseJoinColumns = @JoinColumn(name = "address_id")
)
private List<Address> addresses = new ArrayList<>();

// setAddress() and getAddress() methods

I discovered that it is also possible to split many-to-many relationship to one-to-many and many-to-one using a link entity in Hibernate.

At this point, I just would like to know that what is the most proper approach when building many-to-many relationship in Hibernate? Should I use link entity as mentioned above, or should I use uni or bi-directional relationship? I just would like to stick the most proper one who has more advantageous.

Any help would be appreciated.

1 Answers1

0

I would recommend you to always model this as two bidirectional one-to-many associations, because there is no real many-to-many association in my experience. At some point, someone will come and tell you that the association between your entities suddenly needs an additional attribute. If you modeled this as many-to-many association before, then you will have to potentially rewrite a bunch of code to now handle the new structure.

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58