Skip to main content

Hibernate Primary Key Generation Strategies

There are 4 types of Generation Strategies that can be used to generate Id in hibernate.
  1. AUTO  e.g. strategy = GenerationType.AUTO
  2. IDENTITY e.g. strategy = GenerationType.IDENTITY
  3. SEQUENCE e.g. strategy = GenerationType.SEQUENCE
  4. TABLE e.g. strategy = GenerationType.TABLE
strategy = GenerationType.AUTO
This is the default Generation Strategy that is used by the hibernate. This strategy allows hibernate to decide what strategy to be used to generate the unique key for the table. Strategies used by hibernate can be different for different types of databases used.
strategy = GenerationType.IDENTITY
In this Generation Strategy the hibernate is going to use an identity column. Identity column is a feature that is provided in some of the databases, this is not a generic feature and is provided by a few databases only.
strategy = GenerationType.SEQUENCE
In this Generation Strategy, the hibernate generate unique keys by a sequence hilo. This uses a sequence object to generate a sequence of ids, and sequence.nextval will always give the next value of the sequence.  Databases manages this on their own.
strategy = GenerationType.TABLE
In this Generation Strategy, the hibernate uses a separate table to provide unique key. The table stores the latest value to store the last used primary key so that we can get this value and increment the value to create new primary key.

I would recommend to use  strategy = GenerationType.AUTO because it lets hibernate to use the best generation strategy based on the database we use.

Comments