79614524

Date: 2025-05-09 16:33:56
Score: 4
Natty:
Report link

By the way, if I need to add to both, the names need to match right?

The JPA documentation says that you should only put it on the owning side of a relation, as some of the other answers already mention.

As for why you should not do it anyway, e.g. by trying to make both sides of the relationship the "owner", as suggested by the other answer that says "You actually CAN use @JoinTable on both sides" (can't comment under it due to lacking reputation): If you don't designate either one of the sides as the non-owning side using the mappedBy element of the @ManyToMany annotation, you will get two unidirectional relationships, instead of one bidirectional relationship.

"But I can trick Hibernate into using the same junction table for both of these unidirectional relationships, by using @JoinTable on both sides and specifying the correct columns, so what's the problem?" If Hibernate thinks there are two relationships, it will try to persist it twice.

Consider this scenario, you have the movie and category tables in your database in a many-to-many relationship, tracked by the movie_category table connecting them together. Now you'd like to fetch the movie entity Borat and the category entity comedy, add the category to Borat, and also add the movie to comedy to keep the in-memory model consistent with the database (for some unknown reason you have a bidirectional relationship in this weird example). Hibernate will eventually flush the changes and it will try to write the same thing to the movie_category table twice, once for each relationship, and you will get an error due to the duplicate row (something like <borat_id>, <comedy_category_id> already exists in this table).

I could also imagine it causing more sophisticated, harder-to-debug surprises.

Reasons:
  • Blacklisted phrase (0.5): I need
  • RegEx Blacklisted phrase (1): can't comment
  • RegEx Blacklisted phrase (1.5): reputation
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @JoinTable
  • Low reputation (1):
Posted by: Onur Yilmazer