Skip to main content

Hibernate Sequence Generator using database sequence

Hello friends,
In hibernate many of us face difficulties in linking database sequence with java class.
We want that whenever row inserted by hibernate, it should use the sequence present in database (which was created by our-self) and NOT default hibernate generated  'hibernate_sequence'

Follow these simple steps to link your database sequence with hibernate (Using Sequence generation strategy)

1.Create sequence in the database.
2.Create java class with with jpa/hibernate annotations

You can insert the row in database table directly or through hibernate, this sequence will work without any gaps.

Example
@Id
@Column(name = "SeqId")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INTE_SEQ")
@GenericGenerator(name = "INTE_SEQ", strategy = "org.hibernate.id.SequenceGenerator", parameters = {
@Parameter(name = "sequence", value = "ARCHIVE_SEQ") })
private Integer nid;


/**your code**/

where INTE_SEQ is generator name.
ARCHIVE_SEQ is the name of sequence in the database. It should match with database sequence name

CREATE SEQUENCE  ARCHIVE_SEQ MINVALUE 1  INCREMENT BY 1 START WITH 1 ;


I have implemented above using

1. Hibernate 4
2. Oracle sql 12c database
3. Java 1.8
But you can also try it with hibernate 5

Hope you find this helpful.

Comments