4

I have a entity class

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

}

In certain scenarios, I don't want to load object A, since I already have that object. and same for C also. But these are specific scenarios I don't want to load those objects at all.

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

Note: I am using Criteria to fetch the object right now.

RaceBase
  • 18,428
  • 47
  • 141
  • 202

1 Answers1

2

Since you're using HQL for your queries, you can specify your fetching strategy at runtime based on your condition using the "fetch" keyword, like 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 is 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 the SELECT or JOIN check here.

Community
  • 1
  • 1
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
  • can you modify your example according to my class. Sorry I am confused ;) – RaceBase Feb 05 '13 at 06:49
  • I changed. "I just want this to happen only in specific cases" -- What does your specific case looks like – Jayamohan Feb 05 '13 at 06:52
  • I might be retrieving B object using A object, in that case I dont need loading of A object in B entity. – RaceBase Feb 05 '13 at 06:54
  • I have done this way criteria = getSession().createCriteria(B.class).setFetchMode("a", FetchMode.LAZY) criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria.list(); Still getting the a object – RaceBase Feb 05 '13 at 07:09
  • I have read online/seen posts that EAGER objects can't be LAZY loaded but LAZY objects can be loaded eagerly dynamically – RaceBase Feb 05 '13 at 13:41