25.4.2. Associations
<div class="paragraph">
JPA offers four entity association types:
</div>
<div class="ulist">
@ManyToOne
@OneToOne
@OneToMany
@ManyToMany
</div>And an
@ElementCollection
for collections of embeddables.</div>
Because object associations can be bidirectional, there are many possible combinations of associations. However, not every possible association type is efficient from a database perspective.
</div>
</td>
The closer the association mapping is to the underlying database relationship, the better it will perform.
</div>
On the other hand, the more exotic the association mapping, the better the chance of being inefficient.
</div> </td> </tr> </table> </div>
Therefore, the
@ManyToOne
and the@OneToOne
child-side association are best to represent aFOREIGN KEY
relationship.</div>
The parent-side
@OneToOne
association requires bytecode enhancement so that the association can be loaded lazily. Otherwise, the parent-side is always fetched even if the association is marked withFetchType.LAZY
.</div>
For this reason, it’s best to map
@OneToOne
association using@MapsId
so that thePRIMARY KEY
is shared between the child and the parent entities. When using@MapsId
, the parent-side becomes redundant since the child-entity can be easily fetched using the parent entity identifier.</div>
For collections, the association can be either:
</div>
unidirectional
bidirectional </div>
For unidirectional collections,
Sets
are the best choice because they generate the most efficient SQL statements. UnidirectionalLists
are less efficient than a@ManyToOne
association.</div>
Bidirectional associations are usually a better choice because the
@ManyToOne
side controls the association.</div>
Embeddable collections (
`@ElementCollection
) are unidirectional associations, henceSets
are the most efficient, followed by orderedLists
, whereas bags (unorderedLists
) are the least efficient.</div>
The
@ManyToMany
annotation is rarely a good choice because it treats both sides as unidirectional associations.</div>
For this reason, it’s much better to map the link table as depicted in the Bidirectional many-to-many with link entity lifecycle section. Each
FOREIGN KEY
column will be mapped as a@ManyToOne
association. On each parent-side, a bidirectional@OneToMany
association is going to map to the aforementioned@ManyToOne
relationship in the link entity.</div>
</td>
Just because you have support for collections, it does not mean that you have to turn any one-to-many database relationship into a collection.
</div>
Sometimes, a
@ManyToOne
association is sufficient, and the collection can be simply replaced by an entity query which is easier to paginate or filter.</div> </td> </tr> </table> </div> </div> </div>