I am writing a query against a domain model where (for whatever reason) a one-to-many association is mapped with lazy="false". In my particular query, I'd rather fetch that collection lazily, because I don't care about its contents. How can I reenable laziness for my particular query? Is this possible at all?
So far, I looked at Criteria.setFetchMode
, but FetchMode.LAZY
is merely a deprecated alias for FetchMode.SELECT
...
Changing the mapping would probably be ideal, but I'd rather not risk affecting the existing queries.
Edit: We use Hibernate 3.3.2
To enable lazy loading explicitly you must use “fetch = FetchType. LAZY” on an association that you want to lazy load when you are using hibernate annotations. @OneToMany( mappedBy = "category", fetch = FetchType.
LAZY – Fetch it when you need it. The FetchType. LAZY tells Hibernate to only fetch the related entities from the database when you use the relationship. This is a good idea in general because there's no reason to select entities you don't need for your uses case.
Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.
These data loading strategies we used when one entity class is having references to other Entities like Employee and Phone (phone in the employee). Lazy Loading − Associated data loads only when we explicitly call getter or size method. Use Lazy Loading when you are using one-to-many collections.
The accepted answer is wrong. Hibernate allows you to lazy fetch in criteria something that is by default eager in the mapping. Simply call
criteria.setFetchMode("propertyName", FetchMode.SELECT);
I have tried this and it worked. FetchMode.LAZY is marked deprecated in the source code, and all it does is point to FetchMode.SELECT
Hibernate code:
public static final FetchMode LAZY = SELECT;
In case somebody stumble across this (like me), please refer to this. It appears that this was a Hibernate documentation error, and FetchMode.SELECT
does cause a lazy load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With