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
Newsletter
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

  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big
  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • How to Format Articles for DZone
  • GET, POST, PUT, DELETE: Choosing HTTP Verbs in a Real .NET Core Web API, Not Just by the Textbook

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
DZone Core CORE ·
Sep. 16, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
15.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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