RaceBase
RaceBase

Reputation: 18848

Exclude Loading of specific properties in Hibernate object

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.

Upvotes: 4

Views: 4081

Answers (1)

Jayamohan
Jayamohan

Reputation: 12924

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.

Upvotes: 2

Related Questions