What is the use of the Hibernate @LazyCollection annotation
To give you a hint, it's mainly for performance reasons, you can start reading the following links:
Second Level Cache
Hibernate Documentation
EXTRA = .size() and .contains() won't initialize the whole collection
TRUE = initialize the whole collection on first access
FALSE = Eager-Loading
There's actually no reason to use @LazyCollection
.
The TRUE
and FALSE
values are not needed since the same behavior can be obtained with the JPA FetchType.LAZY
or FetchType.EAGER
.
The EXTRA
value has no equivalent in JPA and was designed for very large collections. When you access an EXTRA
lazy collection for the first time, the collection is not entirely loaded, as it's usually the case with any JPA collection.
Instead, each element is fetched one by one, using a secondary SELECT
. This might sound like an optimization, but it's not because EXTRA
lazy collections are prone to N+1 query issues.
Note that this only works for ordered collections, either List
(s) that are annotated with @OrderColumn
or Map
(s). For bags (e.g. regular List
(s) of entities that do not preserve any certain ordering), the @LazyCollection(LazyCollectionOption.EXTRA)
behaves just like any other LAZY
collection (the collection is fetched entirely upon being accessed for the first time).
If you have a very large collection, then you should not map it at all. Instead, you should map only the @ManyToOne
side, and, instead of a parent-side collection, you should use a paginated JPQL query.
JPQL queries are much easier to tune because you can apply any filtering criteria, and you can paginate the result set.