How to enable bytecode enhancement dirty checking in Hibernate

(Last Updated On: January 29, 2018)

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();
}

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.

Subscribe to our Newsletter

* indicates required
10 000 readers have found this blog worth following!

If you subscribe to my newsletter, you'll get:
  • A free sample of my Video Course about running Integration tests at warp-speed using Docker and tmpfs
  • 3 chapters from my book, High-Performance Java Persistence, 
  • a 10% discount coupon for my book. 
Get the most out of your persistence layer!

Advertisements

18 thoughts on “How to enable bytecode enhancement dirty checking in Hibernate

    1. If you enable that plugin property, Hibernate is going to issue the following WARN message which is very revealing about what this property does:

      Extended enhancement is enabled. Classes other than entities may be modified. You should consider access the entities using getter/setter methods and disable this property. Use at your own risk.

Leave a Reply

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