Chantz
Chantz

Reputation: 5963

Override lazy loading setting for related entities in a hibernate mapping file

I have a mapping file which sets lazy=false for some related entities. This makes sense for a lot of use cases but there are some exceptions. The problem is that I dont want to fetch the related associations at query time for these cases, which are very expensive time-wise.

Example of the mapping for the entity.

<class name="Category" table="category">
    <id name="id" type="string">
      <column length="50" name="id"/>
      <generator class="uuid"/>
    </id>
    <property name="name" type="string">
      <column length="100" name="name" not-null="true"/>
    </property>
    <set inverse="true" lazy="false" name="categorySourcesList">
      <key>
        <column length="50" name="categoryid" not-null="true"/>
      </key>
      <one-to-many class="CategorySource"/>
    </set>
  </class>

My question is, is there a way to override the lazy value which is set in the mapping file, either in the sql-query I custom write or enabling lazy load as one of the parameters in the DAO? or through some annotations?

Upvotes: 2

Views: 6032

Answers (2)

zmf
zmf

Reputation: 9333

Yes, you can override the annotated or xml mapped association fetching strategy.

Hibernate Documentation

    Criteria criteria = session().createCriteria(MyClass.class);
    criteria.add(Restrictions.eq("id", "1234"));        
    criteria.setFetchMode("children",FetchMode.EAGER);
    return (MyClass) criteria.uniqueResult();

This will return you an instance of MyClass with its children eagerly fetched.

Upvotes: 3

Thomas
Thomas

Reputation: 88757

AFAIK you can't override EAGER loading with LAZY but only the other way round.

Thus, you'd need to define the association the be LAZY and override that in the queries using joins. There might be other ways to do that but I'm afraid that's all I know right now.

Upvotes: 2

Related Questions