tags:

views:

2461

answers:

3

I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.

Currently, I have something like:

Session s = HibernateUtil.getSessionFactory().openSession();
MyClass c = (MyClass)session.get(MyClass.class, myClassID);
+1  A: 

You could try something like this: (code off the top of my head)

Criteria crit = session.createCriteria(MyClass.class);
crit.add(Restrictions.eq("id", myClassId));
crit.setFetchMode("myProperty", FetchMode.EAGER);
MyClass myThingy = (MyClass)crit.uniqueResult();

I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.

Mat Mannion
A: 

There is a static initialize(Object) method in the Hibernate main class. You could use that to force loading of your collection:

MyClass c = (MyClass)session.get(MyClass.class, myClassID);
Hibernate.initialize(c.getMySetOfMyClass2());

However, a default value of lazy fetching is just that: a default value. You probably want to override the laziness in the mapping for your particular Set.

Henning
+2  A: 

If you're not using Criteria there's also the JOIN FETCH keyword that will eagerly load the association specified by the join.

session.createQuery("select p from Parent p join fetch p.children c")
Damo