Hibernate Tips: Map generated values


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

The database administrator set up a trigger to generate the value of a database column. How can map this column with Hibernate so that I can use the generated value within my application?

Solution:

You can annotate an entity attribute with @Generated(GenerationTime value), to tell Hibernate that the database will generate the value of the attribute. The GenerationTime enum tells Hibernate when the database will generate the value. It can either do this NEVER, only on INSERT or ALWAYS (on insert and update). Hibernate will then execute an additional query to retrieve the generated value from the database.

The following code snippet shows an example for such an entity mapping.

@Entity
public class Author {

	@Column
	@Generated(GenerationTime.ALWAYS)
	private LocalDateTime lastUpdate;

	…

}

As you can see in the following log output, Hibernate now performs an additional query for each insert and update statement to retrieve the generated value.

10:33:49,612 DEBUG [org.hibernate.SQL] – insert into Author (firstName, lastName, version, id) values (?, ?, ?, ?)
10:33:49,620 DEBUG [org.hibernate.SQL] – select author_.lastUpdate as lastUpda4_0_ from Author author_ where author_.id=?
10:33:49,644 DEBUG [org.hibernate.SQL] – update Author set firstName=?, lastName=?, version=? where id=? and version=?
10:33:49,646 DEBUG [org.hibernate.SQL] – select author_.lastUpdate as lastUpda4_0_ from Author author_ where author_.id=?

Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.

Get it now!

2 Comments

  1. > Hibernate will then execute an additional query to retrieve the generated value from the database.

    Is Hibernate really that limited?

    All modern JDBC drivers can return the generated values (including those stemming from a default value).

    There is no need to run an extra (inefficient) SELECT statement

    1. Avatar photo Thorben Janssen says:

      That only works for primary key values that were generated by an auto incremented column.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.