25.4.2. Associations
<div class="paragraph">
JPA offers four entity association types:
</div>
<div class="ulist">
@ManyToOne@OneToOne@OneToMany@ManyToMany</div>And an
@ElementCollectionfor 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
@ManyToOneand the@OneToOnechild-side association are best to represent aFOREIGN KEYrelationship.</div>
The parent-side
@OneToOneassociation 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
@OneToOneassociation using@MapsIdso that thePRIMARY KEYis 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,
Setsare the best choice because they generate the most efficient SQL statements. UnidirectionalListsare less efficient than a@ManyToOneassociation.</div>
Bidirectional associations are usually a better choice because the
@ManyToOneside controls the association.</div>
Embeddable collections (
`@ElementCollection) are unidirectional associations, henceSetsare the most efficient, followed by orderedLists, whereas bags (unorderedLists) are the least efficient.</div>
The
@ManyToManyannotation 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 KEYcolumn will be mapped as a@ManyToOneassociation. On each parent-side, a bidirectional@OneToManyassociation is going to map to the aforementioned@ManyToOnerelationship 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
@ManyToOneassociation 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>