Associations are fetched lazily by default. You may change this behavior by setting the parameter fetch=FetchType.EAGER
of the annotation @OneToMany
for example. This has the disadvantage, that the association is eagerly fetched each time the respective entity is retrieved from the underlying database. This leads to the so called cartesian product read issue since the respective association is retrieved with the query of the owning entity via LEFT OUTER JOIN
(see JPQL and joins). So, a lot of redundant data might be retrieved from the database, since the OR-Mapper has no interception point where he can prevent to retrieve data cached already. Another way is to overwrite the lazy fetch type in a jpql query (see override fetch type). So the cartesian product read issue does still exist, but you can control when to eagerly fetch an assoctiation and when not.
Both variants have in common, that only one persistent bag can be retrieved at a time for an entity, i.e. only one java.util.List
can be retrieved with the entity for an association annotated with fetch type EAGER
as well as for a fetch join. You may try it out and you will get this error message:
org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
This is not true for sets (e.g. java.util.Set
, java.util.SortedSet
or java.util.LinkedHashSet
). So, if you don’t need to have two or more references to the same entity in one association, you should use a set instead of a list. This shouldn’t be a hard constraint, since a set can still be sorted (see Order associations with JPA).