Using the sequence generator in Hibernate

The generator in hibernate are basically used to generate unique identifiers and generally used for populating the primary key of the objects. As mentioned in the hibernate docs

sequence uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

To use this generator in  the application :

  1. Create a sequence in the database
  2. Annotate primary key with
    @SequenceGenerator(name = "MySequence", sequenceName = "my_seq", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MySequence")
    private Long id;

The max “allocationSize” is by default set to 50
And, by default, the “increment by” is set to 1.

It’s important to note that, the sequence generator work correctly, only when the “allocationSize” and the “increment by” are same, otherwise there is a possibility of getting the “unique constraint violation” exception. therefore, it is better to explicitly define “allocationSize” and “increment by”.

Having a higher allocationSize would increase the performance of your application to some extend but may lead to gaps in the ids of the primary keys.


4 thoughts on “Using the sequence generator in Hibernate

  1. I am having the same problem primary key not found error which saving parent object, but child objects have sequence id

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s