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.5.2.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.

As always, all the code examples used in this article are available over on GitHub.