Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Enabling lazy fetching in Criteria API

Tags:

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

like image 325
meriton Avatar asked Feb 08 '10 15:02

meriton


People also ask

How can we get lazy loading in Hibernate?

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.

What is the use of fetch mode lazy in Hibernate criteria?

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.

How lazy loading works internally in Hibernate?

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.

What is the difference between lazy and eager loading in Hibernate?

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.


2 Answers

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;
like image 107
che javara Avatar answered Oct 01 '22 21:10

che javara


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.

like image 23
Asa Avatar answered Oct 01 '22 22:10

Asa