Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate_Sequence For Each Enitity or Table

By default, Hibernate uses a single global sequence called hibernate_sequence. So if a customer record adds, and id generates 100 while next I add a country record and id generates 101.

in Country Model

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CTRY_ID")
private long ctryID;

in Customer Model

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CUST_ID")
private long custID;

I want separate mechanism for both customer and country tables i.e. Last Id stored in Customer table is 91, so on next record being add, id become 92. And similar way, Last Id stored in Country is 82, so next record, Id should be 83.

How could I achieve this behavior in Spring Boot/Oracle.

like image 817
TAB Avatar asked Jan 27 '23 16:01

TAB


1 Answers

You should try creating a custom sequence using @SequenceGenerator annotation. You can set initial value of sequence initialValue = 1 and allocationSize=1is for increment. If you won't use allocationSize=1 hibernate uses the default allocation size which is 50.

For Country:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="ctry_seq")
@SequenceGenerator(name = "ctry_seq", sequenceName = "ctry_seq", initialValue = 1, allocationSize=1)
@Column(name="CTRY_ID")
private long ctryID;

For Customer:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="cust_seq")
@SequenceGenerator(name = "cust_seq", sequenceName = "cust_seq", initialValue = 1, allocationSize=1)
@Column(name="CUST_ID")
private long custID;
like image 117
Hülya Avatar answered Jan 30 '23 00:01

Hülya