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.
Hibernate uses its default database sequence to generate primary key values. How can I use my own sequence?
The JPA specification provides a set of annotations to define the primary key generation strategy.
First of all, you have to annotate the primary key attribute with the @GeneratedValue annotation and set GenerationType.SEQUENCE as the strategy. This tells Hibernate to use a database sequence to generate the primary key value. If you don’t provide any additional information, Hibernate will use its default sequence.
You can configure the name and schema of the database sequence with a @SequenceGenerator annotation like the one you can see in the following code snippet.
If you now persist a new Author entity, Hibernate will use the configured database sequence “author_seq”. You can see that in the log file, if you activate the logging for SQL statements.
Custom database sequences 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.