Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting FetchMode in native Hibernate

Tags:

java

hibernate

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);
like image 512
Elie Avatar asked Jan 25 '23 00:01

Elie


2 Answers

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.

like image 174
Mat Mannion Avatar answered Jan 26 '23 13:01

Mat Mannion


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")
like image 23
Damo Avatar answered Jan 26 '23 15:01

Damo