DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Implement Hibernate Second-Level Cache With NCache
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Trending

  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • No More Cheap Claude: 4 First Principles of Token Economics in 2026
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Obtain Auto-Generated Keys With Hibernate

How to Obtain Auto-Generated Keys With Hibernate

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

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Sep. 16, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
15.3K Views

Join the DZone community and get the full member experience.

Join For Free

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

Java
xxxxxxxxxx
1
10
 
1
@Entity public class Author implements Serializable { 
2
    
3
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY) 
4
  private Long id; 
5
  
6
  private int age; 
7
  private String name; 
8
  private String genre; 
9
  ... 
10
}


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:

Java
xxxxxxxxxx
1
13
 
1
public void insertAuthorGetAutoGeneratedKeyViaGetId() {
2
  Author author = new Author(); 
3
  
4
  author.setAge(38); 
5
  author.setName("Alicia Tom"); 
6
  author.setGenre("Anthology"); 
7
  
8
  authorRepository.save(author); 
9
  
10
  long pk = author.getId(); 
11
  
12
  System.out.println("Auto generated key: " + pk); 
13
}

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:

Java
xxxxxxxxxx
1
29
 
1
@Repository public class JdbcTemplateDao implements AuthorDao {
2
  
3
  private static final String SQL_INSERT
4
    = "INSERT INTO author (age, name, genre) VALUES (?, ?, ?);"; 
5
  
6
  private final JdbcTemplate jdbcTemplate; 
7
  
8
  public JdbcTemplateDao(JdbcTemplate jdbcTemplate) { 
9
    this.jdbcTemplate = jdbcTemplate; 
10
  } 
11
  
12
  @Override 
13
  @Transactional 
14
  public long insertAuthor(int age, String name, String genre) { 
15
    KeyHolder keyHolder = new GeneratedKeyHolder(); 
16
    jdbcTemplate.update(connection -> { 
17
      PreparedStatement ps = connection .prepareStatement(SQL_INSERT,
18
         Statement.RETURN_GENERATED_KEYS); 
19
      
20
      ps.setInt(1, age); 
21
      ps.setString(2, name); 
22
      ps.setString(3, genre); 
23
      
24
      return ps; 
25
    }, keyHolder); 
26
    
27
    return keyHolder.getKey().longValue(); 
28
  } 
29
}


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:

Java
xxxxxxxxxx
1
 
1
// alternative 1 
2
PreparedStatement ps = connection .prepareStatement(SQL_INSERT, new String[]{"id"}); 
3
   
4
// alternative 2 
5
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:

Java
x
17
 
1
@Repository 
2
public class SimpleJdbcInsertDao implements AuthorDao {
3
4
  private final SimpleJdbcInsert simpleJdbcInsert; 
5
  
6
  public SimpleJdbcInsertDao(DataSource dataSource) {
7
    this.simpleJdbcInsert = new SimpleJdbcInsert(dataSource) 
8
      .withTableName("author").usingGeneratedKeyColumns("id"); 
9
  }
10
  
11
  @Override
12
  @Transactional 
13
  public long insertAuthor(int age, String name, String genre) {
14
    return simpleJdbcInsert.executeAndReturnKey( 
15
      Map.of("age", age, "name", name, "genre", genre)).longValue(); 
16
  } 
17
}


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.  

Spring Framework Database Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Minimizing Latency in Kafka Streaming Applications That Use External API or Database Calls
  • Implement Hibernate Second-Level Cache With NCache
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook