eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

When building our persistence layer with Hibernate, we often need to generate or populate certain entity attributes automatically. This can include assigning default values, generating unique identifiers, or applying custom generation logic.

Hibernate 6.2 introduces two new interfaces, BeforeExecutionGenerator and OnExecutionGenerator, which allow us to generate values for our entity attributes automatically. These interfaces replace the deprecated ValueGenerator interface.

In this tutorial, we’ll explore these new interfaces to generate attribute values before and during SQL statement execution.

2. Application Setup

Before we discuss how to use the new interfaces to generate entity attribute values, let’s set up a simple application that we’ll use throughout this tutorial.

2.1. Dependencies

Let’s start by adding the Hibernate dependency to our project’s pom.xml file:

<dependency>
    <groupId>org.hibernate.orm</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.6.0.Final</version>
</dependency>

2.2. Defining the Entity Class and Repository Layer

Now, let’s define our entity class:

@Entity
@Table(name = "wizards")
class Wizard {

    @Id
    private UUID id;

    private String name;

    private String house;

    // standard setters and getters

}

The Wizard class is the central entity in our example, and we’ll be using it to learn how to automatically generate attribute values in the upcoming sections.

With our entity class defined, we’ll create a repository interface that extends JpaRepository to interact with our database:

@Repository
interface WizardRepository extends JpaRepository<Wizard, UUID> {
}

3. The BeforeExecutionGenerator Interface

The BeforeExecutionGenerator interface allows us to generate attribute values before any SQL statement execution. It’s a simple interface with two methods: generate() and getEventTypes().

To understand its usage, let’s look at a use case where we want to automatically assign a random house to each new Wizard entity that we insert in our database.

To achieve this, we’ll create a custom generator class that implements the BeforeExecutionGenerator interface:

class SortingHatHouseGenerator implements BeforeExecutionGenerator {

    private static final String[] HOUSES = { "Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin" };
    private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();

    @Override
    public Object generate(SharedSessionContractImplementor session, Object owner, Object currentValue, EventType eventType) {
        int houseIndex = RANDOM.nextInt(HOUSES.length);
        return HOUSES[houseIndex];
    }

    @Override
    public EnumSet<EventType> getEventTypes() {
        return EnumSet.of(EventType.INSERT);
    }

}

In our generate() method, we randomly select one of the four Hogwarts houses and return it. We also specify the EventType.INSERT in our getEventTypes() method to tell Hibernate that this generator should only be applied during new entity creation.

To use our SortingHatHouseGenerator class, we need to create a custom annotation and meta-annotate it with @ValueGenerationType:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@ValueGenerationType(generatedBy = SortingHatHouseGenerator.class)
@interface SortHouse {
}

Now, we can apply our custom @SortHouse annotation to the house attribute of our Wizard entity class:

@SortHouse
private String house;

Then, whenever we save a new Wizard entity, our generator automatically assigns it a random house:

Wizard wizard = new Wizard();
wizard.setId(UUID.randomUUID());
wizard.setName(RandomString.make());

Wizard savedWizard = wizardRepository.save(wizard);

assertThat(savedWizard.getHouse())
  .isNotBlank()
  .isIn("Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin");

It’s important to note that if we need to reference our entity instance or access the current value of the field where we place our annotation, we can cast the owner and currentValue parameters to the desired types in our generate() method.

4. The OnExecutionGenerator Interface

The OnExecutionGenerator interface allows us to generate attribute values during SQL statement execution. This is useful when we want the database to generate the values for us.

This interface has a few more methods compared to the BeforeExecutionGenerator interface.

For this demonstration, let’s take an example where we add a new updatedAt attribute to our Wizard entity class. We want to automatically set our new attribute to the current timestamp whenever a Wizard entity is inserted or updated.

First, we’ll create a custom generator class that implements the OnExecutionGenerator interface:

class UpdatedAtGenerator implements OnExecutionGenerator {

    @Override
    public boolean referenceColumnsInSql(Dialect dialect) {
        return true;
    }

    @Override
    public boolean writePropertyValue() {
        return false;
    }

    @Override
    public String[] getReferencedColumnValues(Dialect dialect) {
        return new String[] { dialect.currentTimestamp() };
    }

    @Override
    public EnumSet<EventType> getEventTypes() {
        return EnumSet.of(EventType.INSERT, EventType.UPDATE);
    }

}

In our getReferencedColumnValues() method, we return an array containing the built-in SQL function to generate the current timestamp. This references JPQL’s current_timestamp function.

Then, in our referenceColumnsInSql() method, we return true to indicate that our updatedAt attribute should be included in the SQL statement’s column list.

Additionally, we set the writePropertyValue() method to return false to ensure that no value is passed as a JDBC parameter, since it’s generated by the database.

Similarly, we’ll create a custom annotation for our UpdatedAtGenerator class:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@ValueGenerationType(generatedBy = UpdatedAtGenerator.class)
@interface GenerateUpdatedAtTimestamp {
}

Then, we’ll apply our custom @GenerateUpdatedAtTimestamp to our new updatedAt attribute in our Wizard entity class:

@GenerateUpdatedAtTimestamp
private LocalDateTime updatedAt;

Now, whenever we save or update a Wizard entity, the database automatically sets the updatedAt attribute to the current timestamp:

Wizard savedWizard = wizardRepository.save(wizard);
LocalDateTime initialUpdatedAtTimestamp = savedWizard.getUpdatedAt();

savedWizard.setName(RandomString.make());
Wizard updatedWizard = wizardRepository.save(savedWizard);

assertThat(updatedWizard.getUpdatedAt())
  .isAfter(initialUpdatedAtTimestamp);

We can also use the OnExecutionGenerator interface to generate values based on custom SQL expressions. Let’s add another attribute named spellPower to our Wizard entity class and calculate its value based on the day we create it:

class SpellPowerGenerator implements OnExecutionGenerator {

    // ... same as above

    @Override
    public String[] getReferencedColumnValues(Dialect dialect) {
        String sql = "50 + (EXTRACT(DAY FROM CURRENT_DATE) % 30) * 2";
        return new String[] { sql };
    }

}

We’ll create a corresponding @GenerateSpellPower annotation for our SpellPowerGenerator class as we’ve seen earlier and apply it to our new spellPower attribute in our Wizard entity class:

@GenerateSpellPower
private Integer spellPower;

Now, when we create a new Wizard entity, our defined SQL expression sets its spellPower attribute value automatically:

Wizard savedWizard = wizardRepository.save(wizard);

assertThat(savedWizard.getSpellPower())
  .isNotNull()
  .isGreaterThanOrEqualTo(50);

5. Conclusion

In this article, we explored the new BeforeExecutionGenerator and OnExecutionGenerator interfaces in Hibernate to automatically generate values for our entity attributes.

We use the BeforeExecutionGenerator interface when we need to generate values before executing the SQL statement. This is ideal for scenarios where we want to apply Java-based logic, as demonstrated with our random house assignment.

On the other hand, we use the OnExecutionGenerator interface when we want the database to generate the values as part of the SQL statement execution. This is particularly useful for leveraging database functions and SQL expressions, as we saw in our updatedAt timestamp and spellPower examples.

The choice between these interfaces depends on whether the value generation logic is better suited for Java code or database operations.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)