Hibernate Extended Bytecode Enhancement
In Hibernate, there’s a mystical option enableExtendedEnhancement
intended for fine-tuning of the bytecode enhancement. This option is not described well in the documentation. This article explains what it is, how to use it, and what benefits it may bring to you.
Project Configuration
To demo the effect of Hibernate’s extended enhancement, we’ll start with a simple entity class Cat
that contains two fields: an automatically generated id and a name:
By the way, the full code for the article is available at GitHub — this is a very simple demo project using Java 14, Hibernate 5.4, and JUnit 5.
Dirty Checking
Hibernate can automatically save an attached entity instance on flush if you’ve made any changes to it. By default, it does to by keeping the initial state of the object in memory and comparing it to the actual state before flushing. This process is called dirty checking.
Suppose we want to get an entity from the database, update its field and save it back. Thanks to this dirty checking feature, this is very easy:
We update a field of an entity, but we don’t need to ask Hibernate specifically to save the changes —thanks to dirty checking, Hibernate can determine that a field was updated.
However, keeping the whole initial state of the object in memory is costly, and doing a field-by-field comparison before flushing wastes time. So there’s another mechanism in Hibernate for dirty checking, that takes advantage of Hibernate’s bytecode enhancement.
Bytecode Enhancement
Just by adding the hibernate-enhance-maven-plugin
to our project, we enable Hibernate to instrument our…