21

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

meriton
  • 68,356
  • 14
  • 108
  • 175

3 Answers3

32

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;
che javara
  • 748
  • 1
  • 8
  • 18
  • 1
    This worked for me - I was using Criteria.DISTINCT_ROOT_ENTITY with setFirstResult & setMaxResults and getting too few results. – blank Jun 22 '12 at 06:09
  • 3
    @Che javara - just tried this and not working for me. I am using Hibernate 3.6.10. Searched the code for uses and none looked to be cases of Hibernate skipping the loading of a collection/association. Got any suggestions on where to look? – mikemil Nov 07 '13 at 20:11
4

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.

Community
  • 1
  • 1
Asa
  • 1,624
  • 15
  • 19
-6

I am not an expert myself, but browsing through the Hibernate book and consulting with a colleague didn't give me any hint that this would be possible, rather the contrary.

Yours seems to be an unusual situation, not covered by Hibernate. The typical use case is the opposite: to use lazy fetching by default, and selectively enable eager fetching for queries where it is justified.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • I didn't find anything either. It appears one better does not deviate from hibernate's defaults. I have worked around the problem by projecting. (I didn't need the entire entities, though I'd rather have avoided defining a new DTO). – meriton Feb 09 '10 at 15:12