Search code examples
mysqldatabasehibernatehibernate-mapping

@OneToMany with association table in hibernate


I'm taking a course on hibernate. The instructor discussed something about Databases. When we have a 1-N relationship, and the optionality is 0. It is a good idea to have a junction table to avoid null values. Just that didn't feel right for me, and I hope someone explains that. To be clear, the topic is basically about hibernating, and I'm not sure that is related.

enter image description here


Solution

  • I consider association table for one-to-many relation a bad advice.

    Firstly, the argument that you avoid null values is wrong - if you have parent child relation, you put the FK on the child table. Thus, if the number of children is zero, there are simply no records with FK pointing to parent - no null values are introduced.

    Secondly, proposed mapping is less efficient when compared to FK on the child table. See The best way to map a @OneToMany relationship with JPA and Hibernate:

    For a DBA, this looks more like a many-to-many database association than a one-to-many relationship, and it’s not very efficient either. Instead of two tables, we now have three tables, so we are using more storage than necessary. Instead of only one Foreign Key, we now have two of them. However, since we are most likely going to index these Foreign Keys, we are going to require twice as much memory to cache the index for this association. Not nice!

    Similarly, in 14 High-Performance Java Persistence Tips, unidirectional @OneToMany (Hibernate's way to map one-to-many with association table) is listed as one of least-efficient relationships.

    And lastly, the title @JoinTable instead @OneToMany is misleading - @JoinTable can be used to configure unidirectional @OneToMany relationship, it does not replace it. See JPA - Using @JoinTable in @OneToMany association:

    @JoinTable annotation can be used in an association to customize the generated join table or to map the existing join table. In the following example, we will demonstrates how to use this annotation with @OneToMany association.