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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Incident Response Guide
  • Database Integration Tests With Spring Boot and Testcontainers
  • Java String Templates Today
  • Mainframe Development for the "No Mainframe" Generation

Trending

  • Incident Response Guide
  • Database Integration Tests With Spring Boot and Testcontainers
  • Java String Templates Today
  • Mainframe Development for the "No Mainframe" Generation
  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.

Anghel Leonard user avatar by
Anghel Leonard
CORE ·
Sep. 16, 20 · Tutorial
Like (4)
Save
Tweet
Share
13.43K 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.

Trending

  • Incident Response Guide
  • Database Integration Tests With Spring Boot and Testcontainers
  • Java String Templates Today
  • Mainframe Development for the "No Mainframe" Generation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: