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 :
- Create a sequence in the database
CREATE SEQUENCE my_seq START WITH 1 INCREMENT BY 1;
- Annotate primary key with
@Id @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.