Exclude Loading specific properties into a Hibernate object

I have an entity class

class B{
    @ManyToOne(fetch = FetchType.EAGER)
    private A a;
    @ManyToOne(fetch = FetchType.LAZY)
    private C c;

      

}

In some scenarios, I don't want to load object A, since I already have this object. and the same for C as well. But these are specific scenarios. I don't want to load these objects at all.

is there any way hibernate can fail to load certain properties of entity object. {no Eager / Fetch suggestions. I just want this to happen only in certain cases]

Note. I am using criteria to retrieve an object right now.

+3


source to share


1 answer


Since you are using HQL

for your queries, you can specify the fetch strategy at runtime depending on your state using the "fetch" command, as shown below:

List result = sess.createCriteria(B.class)
    .add( Restrictions.like("name", "yourcondition%") )
    .setFetchMode("a", FetchMode.EAGER)
    .setFetchMode("c", FetchMode.LAZY)
    .list();

      

Edit:



Since FetchMode.EAGER and FetchMode.LAZY are deprecated use FetchMode.SELECT or FetchMode.JOIN

List result = sess.createCriteria(B.class)
    .add( Restrictions.like("name", "yourcondition%") )
    .setFetchMode("a", FetchMode.JOIN)
    .setFetchMode("c", FetchMode.SELECT)
    .list();

      

If you want to avoid SELECT or JOIN checking here .

+2


source







All Articles