How to enable bytecode enhancement dirty checking in Hibernate

Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?

Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.

So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!

Introduction

Hibernate runs the automatic dirty checking mechanism during flush-time, and any managed entity state change is translated into an UPDATE SQL statement. The default dirty checking mechanism uses Java reflection and goes through every property of every managed entity.

If the Persistence Context has few entities, this process might go unnoticed, but, if we’re dealing with many entities or the entities have many properties (e.g. a legacy database Domain Model mapping), then the reflection-based dirty checking might have an associated performance impact.

Hibernate offers support for instrumenting entity bytecode for three use cases:

  • lazy initialization (allows entity attributes to be fetched lazily)
  • dirty tracking (the entity tracks its own property changes)
  • association management (allows automatic sides synchronization for bidirectional associations)

Although it featured a bytecode enhancement tool since version 3.x, even in Hibernate 4.x the bytecode enhancement mechanism was not completely implemented for dirty checking.

It’s Hibernate 5 time

Among many other features, Hibernate 5.x comes with a brand new bytecode enhancement implementation which also takes care of the dirty checking mechanism.
Although bytecode enhancement can be done at compile-time, runtime or deploy time, the compile-time alternative is preferred for the following reasons:

  • the enhanced classes can be covered by unit tests
  • the Java EE application server or the stand-alone container (e.g. Spring) can bootstrap faster because there’s no need to instrument classes at runtime or deploy-time
  • class loading issues are avoided since the application server doesn’t have to take care of two versions of the same class (the original and the enhanced one).

To instrument all @Entity classes, you need to add the following Maven plugin:

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

After the Java classes are compiled, the plugin goes through all entity classes and modifies their bytecode according to the instrumentation options chosen during configuration.

When enabling the dirty tracking option, Hibernate will track property changes through the following mechanism.
The $$_hibernate_tracker attribute stores every property change, and every setter method will call the $$_hibernate_trackChange method.

@Transient
private transient DirtyTracker $$_hibernate_tracker;

public void $$_hibernate_trackChange(String paramString) {
    if (this.$$_hibernate_tracker == null) {
        this.$$_hibernate_tracker = new SimpleFieldTracker();
    }
    this.$$_hibernate_tracker.add(paramString);
}

Considering the following original Java entity class setter method:

public void setTitle(String title) {
    this.title = title;
}

Hibernate transforms it to the following bytecode representation:

public void setTitle(String title) {
    if(!EqualsHelper.areEqual(this.title, title)) {
        this.$$_hibernate_trackChange("title");
    }
    this.title = title;
}

When the application developer calls the setTitle method with an argument that differs from the currently stored title,
the change is going to be recorded in the $$_hibernate_tracker class attribute.

During flushing, Hibernate inspects the $$_hibernate_hasDirtyAttributes method to validate if an entity is dirty.
The $$_hibernate_getDirtyAttributes method gives a String[] containing all dirty properties.

public boolean $$_hibernate_hasDirtyAttributes() {
    return $$_hibernate_tracker != null && 
        !$$_hibernate_tracker.isEmpty();
}

public String[] $$_hibernate_getDirtyAttributes() {
    if($$_hibernate_tracker == null) {
        $$_hibernate_tracker = new SimpleFieldTracker();
    }
    return $$_hibernate_tracker.get();
}

I'm running an online workshop on the 20-21 and 23-24 of November about High-Performance Java Persistence.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

Although bytecode enhancement dirty tracking can speed up the Persistence Context flushing mechanism,
if the size of the Persistence Context is rather small, the improvement is not that significant.

The entity snapshot is still saved in the Persistence Context even when using bytecode enhancement.
For this reason, keeping the Persistence Context in reasonable boundaries holds on no matter the dirty tracking mechanism in use.

Transactions and Concurrency Control eBook

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.