Video in progress

Strong Middle 🐻 Hibernate and JPA

What does Hibernate bytecode enhancement give you, and what does it cost to turn on?

At build time the entity classes are modified: lazy basic attributes (for example, a large @Lob), a truly lazy @OneToMany on the mappedBy side of a @OneToOne, field-level dirty tracking, and automatic synchronization of associations. The cost is a build plugin, unexpected behavior when debugging, and differences in tests.

📖 Answer

Normally Hibernate can't get inside an entity: for lazy loading it creates a proxy, and for changes it compares against a snapshot. With enhancement, interceptors are added to the class's bytecode, and every getter/setter signals Hibernate.

Maven:

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

When it's worth it:

  • the Document entity has a 5 MB content column, but a list needs only the title: @Basic(fetch = LAZY) works only with enhancement;
  • an inverse @OneToOne must be LAZY;
  • in very large persistence contexts where flush time is a problem (dirty tracking removes the comparison).

The cost:

  • a step is added to the build, and tests run in the IDE without enhancement behave differently;
  • lazy attributes are loaded by "fetch group": touching one lazy field sometimes pulls in other lazy fields too, which you manage with @LazyGroup;
  • libraries that access a field directly through reflection, without a getter, can give unexpected results.

My approach: I first try to solve the problem with the schema or a DTO (splitting the big column into a separate table is often simpler). I turn on enhancement when there is a clear, measured reason.