In a relational database system, a one-to-many association between links two tables based on a Foreign Key column so that the child table record references the Primary Key of the parent table row.
As straightforward as it might be in a RDBMS, when it comes to JPA, the one-to-many database association can be represented either through a
@ManyToOne or a
@OneToMany association since the OOP association can be either unidirectional or bidirectional.
@ManyToOne annotation allows you to map the Foreign Key column in the child entity mapping so that the child has an entity object reference to its parent entity. This is the most natural way of mapping a database one-to-many database association, and, usually, the most efficient alternative too.
For convenience, to take advantage of the entity state transitions and the dirty checking mechanism, many developers choose to map the child entities as a collection in the parent object, and, for this purpose, JPA offers the
As I explained in my book, many times, you are better off replacing collections with a query, which is much more flexible in terms of fetching performance. However, there are times when mapping a collection is the right thing to do, and then you have two choices:
- a unidirectional
- a bidirectional
The bidirectional association requires the child entity mapping to provide a
@ManyToOne annotation, which is responsible for controlling the association.
One the other hand, the unidirectional
@OneToMany association is simpler since it’s just the parent-side which defines the relationship. In this article, I’m going to explain the caveats of
@OneToMany associations, and how you can overcome them.
There are many ways to map the
@OneToMany association. We can use a List or a Set. We can also define the
@JoinColumn annotation too. So, let’s see how all these work.