How to Obtain Auto-Generated Keys With Hibernate
How to obtain auto-generated keys in a Hibernate - Spring Boot application.
Join the DZone community and get the full member experience.
Join For FreeConsider the following Author
entity that delegates the keys generation to the database system:
xxxxxxxxxx
public class Author implements Serializable {
strategy = GenerationType.IDENTITY) (
private Long id;
private int age;
private String name;
private String genre;
...
}
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:
xxxxxxxxxx
public void insertAuthorGetAutoGeneratedKeyViaGetId() {
Author author = new Author();
author.setAge(38);
author.setName("Alicia Tom");
author.setGenre("Anthology");
authorRepository.save(author);
long pk = author.getId();
System.out.println("Auto generated key: " + pk);
}
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:
xxxxxxxxxx
public class JdbcTemplateDao implements AuthorDao {
private static final String SQL_INSERT
= "INSERT INTO author (age, name, genre) VALUES (?, ?, ?);";
private final JdbcTemplate jdbcTemplate;
public JdbcTemplateDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public long insertAuthor(int age, String name, String genre) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection .prepareStatement(SQL_INSERT,
Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, age);
ps.setString(2, name);
ps.setString(3, genre);
return ps;
}, keyHolder);
return keyHolder.getKey().longValue();
}
}
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:
xxxxxxxxxx
// alternative 1
PreparedStatement ps = connection .prepareStatement(SQL_INSERT, new String[]{"id"});
// alternative 2
PreparedStatement ps = connection .prepareStatement(SQL_INSERT, new int[] {1});
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:
public class SimpleJdbcInsertDao implements AuthorDao {
private final SimpleJdbcInsert simpleJdbcInsert;
public SimpleJdbcInsertDao(DataSource dataSource) {
this.simpleJdbcInsert = new SimpleJdbcInsert(dataSource)
.withTableName("author").usingGeneratedKeyColumns("id");
}
public long insertAuthor(int age, String name, String genre) {
return simpleJdbcInsert.executeAndReturnKey(
Map.of("age", age, "name", name, "genre", genre)).longValue();
}
}
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.
Opinions expressed by DZone contributors are their own.
Comments