How to Obtain Auto-Generated Keys With Hibernate

DZone 's Guide to

How to Obtain Auto-Generated Keys With Hibernate

How to obtain auto-generated keys in a Hibernate - Spring Boot application.

· Java Zone ·
Free Resource

Consider the following Author entity that delegates the keys generation to the database system:


Now, let's see how to retrieve the database auto-generated primary keys via getId(), JdbcTemplate and SimpleJdbcInsert.

Retrieve Auto-Generated Keys via getId() 

In JPA style, retrieving the auto-generated keys can be done via getId() as in the following example:


Retrieve Auto-Generated Keys via JdbcTemplate 

Using JdbcTemplate to retrieve the auto-generated keys can be done via the update() method. This method comes in different flavors, but the signature needed here is: 

public int update(PreparedStatementCreator ps,KeyHolder generatedKeyHolder) throws DataAccessException

The PreparedStatementCreator is a functional interface that takes an instance of java.sql.Connection and return a java.sql.PreparedStatement object. The KeyHolder object contains the auto-generated key returned by the update() method. In code lines:


In the above example, the PreparedStatement is instructed to return the auto-generated keys via Statement.RETURN_GENERATED_KEYS. Alternatively, the same thing can be accomplished as follows:


Retrieve auto-generated keys via SimpleJdbcInsert

Consequently, calling SimpleJdbcInsert.executeAndReturnKey() method to insert a new record to author table and get back the auto-generated key:


The complete application is available on GitHub.

If you liked this article, then you'll my book containing 150+ performance items - Spring Boot Persistence Best Practices

This book helps every Spring Boot developer to squeeze the performances of the persistence layer.  

databases, hibernate, java, persistence, spring boot

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}