Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
My database supports auto-incremented columns. How can I use them as primary keys in Hibernate?
Don’t want to read? You can watch it here!
JPA and Hibernate support different strategies to generate primary key values. One of them is the identity strategy which uses an auto-incremented database column.
If you want to use this strategy, you have to annotate the primary key attribute @Id and with the @GeneratedValue annotation and set the strategy attribute to GenerationType.IDENTITY.
The following code snippet shows an example of this annotation
If you now persist a new Author entity, Hibernate will use the auto-incremented database column to generate the primary key value. You can see that in the log file if you activate the logging for SQL statements.
Databases handle auto-incremented columns very efficiently. But you need to be aware that Hibernate has to perform the INSERT statement immediately to get the primary key value. This prevents it from using different performance optimizations that rely on the delayed execution of database operations.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
Auto-incremented database columns are only 1 out of 4 options to generate primary key values. I get into more details about the different strategies in How to generate primary keys with JPA and Hibernate.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.