How to use sequence generator on Hibernate (Be careful with unique constraint violation)

Sequences are used to generate a ID when you do insert into a table on your database.

Use the following command to create a sequence on your Oracle database.

CREATE SEQUENCE mySequence START WITH 1 INCREMENT BY 1;

How to map on Hibernate

@Id
@SequenceGenerator(name = "mySequence", sequenceName = "mySequence", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="mySequence")
private Long id;

Pay attention to “allocationSize”, that param need to be equal the “INCREMENT BY”,
otherwise may to show errors like “unique constraint violation”.

With the “allocationSize” larger then “INCREMENT BY”, you will generate a gap between the application sequence mapped by Hibernate with your database.