Obviously, criteria queries are more difficult to read if they get more complex—a good reason to prefer them for dynamic and programmatic query generation, but to use externalized HQL and JPA QL for predefined queries.
A proxy is initialized if you call any method that is not the identifier getter
method, a collection is initialized if you start iterating through its elements or if
you call any of the collection-management operations, such as size() and contains().
Hibernate provides an additional setting that is mostly useful for large collections; they can be mapped as extra lazy.
@OneToMany
@org.hibernate.annotations.LazyCollection(
org.hibernate.annotations.LazyCollectionOption.EXTRA
)
private Set<Bid> bids = new HashSet<Bid>();
The collection is no longer
initialized if you call size(), contains(), or isEmpty()—the database is queried
to retrieve the necessary information. If it’s a Map or a List, the operations containsKey()
and get() also query the database directly.