Setting FetchMode in native Hibernate

前端 未结 3 1340
长情又很酷
长情又很酷 2021-01-14 00:46

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

相关标签:
3条回答
  • 2021-01-14 01:11

    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.

    0 讨论(0)
  • 2021-01-14 01:13

    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.

    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题