Property Lazy Fetching

Property lazy fetching can be really useful especially when you have a field which is binary data and you don’t want to fetch this property every time the object is loaded. Lets say you have an entity class Foo as below.

package entities;
public class Foo {
	private String id;
	private String filename;
	private byte[] filedata;
}

and the mapping file is as follows

<hibernate-mapping package="entities">
        <class name="Foo">
		<id name="id" column="id" length="36">
			<generator class="uuid" />
		</id>
		<property name="filename" />
		<property name="filedata" lazy="true"/>
	</class>
</hibernate-mapping>

Here as you may have noticed filedata property is marked as lazy=”true”. However this attribute is ignored by Hibernate unless the class is bytecode instrumented. Therefore to enable lazy fetching for properties the classes must be instrumented. Luckily there is an ant task for this and if you use maven for the build process you can call it simply by calling maven-ant-plugin.

   <plugin>
      <artifactId>maven-antrun-plugin</artifactId>
      <executions>
           <execution>
               <id>instrument</id>
                   <phase>compile</phase>
                       <configuration>
                        <tasks>
                           <echo>Instrumenting classes</echo>
                           <taskdef name="instrument" classname="org.hibernate.tool.instrument.cglib.InstrumentTask">
                               <classpath>
                                   <path refid="maven.dependency.classpath" />
                                   <path  refid="maven.plugin.classpath" />
                               </classpath>
                           </taskdef>
                          <instrument verbose="true">
                             <fileset dir="${project.build.outputDirectory}">
                                <include name="**/entities/Foo.class" />
                             </fileset>
                          </instrument>
                    </tasks>
                    </configuration>
                    <goals>
                            <goal>run</goal>
                    </goals>
               </execution>
           </executions>
           <dependencies>
               <dependency>
                       <groupId>org.hibernate</groupId>
                       <artifactId>hibernate</artifactId>
                       <version>3.2.1.ga</version>
               </dependency>
          </dependencies>
          </plugin>

1 Comment »

  1. Jason said

    Thank you very much for sharing this information.That is exactly what I was searching for.

RSS feed for comments on this post · TrackBack URI

Leave a Comment