@Basic(fetch = FetchType.LAZY) does not work?

Khosro picture Khosro · Jan 21, 2010 · Viewed 26.5k times · Source

I use JPA (Hibernate) with Spring. When i want to lazy load a Stirng property i use this syntax:

@Lob
@Basic(fetch = FetchType.LAZY)
public String getHtmlSummary() {
    return htmlSummary;
}

But when i look at the sql that hibernate creates, it seems this property is not lazy loaded? I also use this class org.hibernate.tool.instrument.javassist.InstrumentTask in ANT script to instrument this property but it seems it does not work.

Please help me.

Khosro.

Answer

Vlad Mihalcea picture Vlad Mihalcea · Mar 31, 2016

First of all, you should know that the JPA specs clearly specifies that LAZY is only a hint to JPA providers, so it's not a mandatory requirement.

For basic type lazy fetching to work, you need to enable bytecode enhancement and explicitly set the enableLazyInitialization configuration property to true:

<plugin>
    <groupId>org.hibernate.orm.tooling</groupId>
    <artifactId>hibernate-enhance-maven-plugin</artifactId>
    <version>${hibernate.version}</version>
    <executions>
        <execution>
            <configuration>
                <enableLazyInitialization>true</enableLazyInitialization>
            </configuration>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>