Issue
Say I have an entity Parent with a related entity Child (nullable) with a @OneToMany(fetch = FetchType.LAZY)
relationship
In my action bean, would the following code initialise the child entity?
if(parent.getChild()!=null){
hasChild = true;
}
I see in the docs it says Lazy collection fetching: a collection is fetched when the application invokes an operation upon that collection. This is the default for collections.
but wasn't sure if a null check is classed as an operation
Thanks
Solution
No, a null
check is not enough to reliably trigger lazy loading. You need to perform an operation that would require the presence of actual data, like calling size()
on a Collection
or any getter of your child object.
Please note that you will need to access the lazily loaded attribute inside a transaction.
It is not guaranteed that the lazily loaded attribute will not be loaded, even if you do nothing. FetchType.LAZY
is only a hint to the persistence provider, so testing for lazy loading may result in fragile tests.
Answered By - kostja
Answer Checked By - Senaida (JavaFixing Volunteer)