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);
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.
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")
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