Bytecode Enhancement

Changing the Entity Classes at Build Time

Bytecode enhancement rewrites your compiled entity classes so that they cooperate with Hibernate. It enables:

FeatureWhat you get
Lazy initializationreal lazy loading of basic fields (@Basic(fetch = LAZY) on a big description or image column) and of @OneToOne on the non-owning side
Dirty trackingsetters record which fields changed, so flush needs no snapshot comparison
Association managementsetting one side of a bidirectional relationship updates the other side

Enable It

<plugin>
    <groupId>org.hibernate.orm.tooling</groupId>
    <artifactId>hibernate-enhance-maven-plugin</artifactId>
    <version>${hibernate.version}</version>        <!-- Spring Boot manages this property -->
    <executions>
        <execution>
            <goals><goal>enhance</goal></goals>
            <configuration>
                <enableLazyInitialization>true</enableLazyInitialization>
                <enableDirtyTracking>true</enableDirtyTracking>
                <enableAssociationManagement>false</enableAssociationManagement>
            </configuration>
        </execution>
    </executions>
</plugin>

Note: In recent Hibernate 6 versions lazy initialization and dirty tracking are on by default when the plugin runs, and those two flags are deprecated. Gradle users apply the org.hibernate.orm plugin with a hibernate { enhancement { } } block.

Lazy Basic Field Example

@Entity
public class Product {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String name;
    private BigDecimal price;

    @Basic(fetch = FetchType.LAZY)          // only honoured with bytecode enhancement
    @Column(columnDefinition = "TEXT")
    private String description;             // long HTML; not needed in product lists
}

SQL Log

GET /api/products/7 then GET /api/products/7/description

Example output

select p1_0.id,p1_0.name,p1_0.price from products p1_0 where p1_0.id=?
select p1_0.description from products p1_0 where p1_0.id=?      <- loaded on first access

Tip: Enhancement adds build complexity. Many teams skip it and use DTO projections to avoid loading big columns. Use it when profiling shows dirty checking or big columns are a real cost.