Hibernate Tips: How to use a custom database sequence

By Thorben Janssen

Mapping, Primary Key

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.  

Learn more:

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.


Mapping, Primary Key

About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Repl​​​​​y

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. am having problem if a am using generation type- Sequence and giving allocation size and Im size but it take default oracle sequence and giving an error how can solve this …please guide

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}