Search code examples
javahibernatejpajoinhibernate-mapping

Why would you use @JoinTable annotation instead of Unidirectional @OneToMany annotation within Java


I am learning persistence with Hibernate (and JPA) on Udemy and the presenter explains an alternative to the previous associations discussed (unidirectional OneToOne, bidirectional OneToOne, Unidirectional OneToMany, bidirectional OneToMany), called the @JoinTable JPA annotation.

He mentions that sometimes only a small selection of the "Many" entities are associated with a specific kind of "One" entities and that we don't want a field on the "Many" entity to embody the association with the "One" entity since that field will remain null for most instances. He goes on to recommend the @JoinTable for this situation.

My question is, considering the effect of the @JoinTable option on the Java entities, why not just use the Unidirectional @OneToMany annotation on the "One" entity and leave the "Many" entity as-is? Which additional features would @JoinTable bring to the situation from within Java beyond what Unidirectional @OneToMany brings?


Solution

  • Then he is clearly wrong, @JoinTable is definitely not necessary here and will introduce overhead in terms of memory (more data to store) and time complexity (another table to join).

    You're right about that you only need @JoinColumn to map one-to-one and one-to-many relationships (and mappedBy on the other side if it should be bidirectional).

    P.S.: I would consider going further with this course, as it seems to be flawed even with the very basics of jpa.