@SequenceGenerator(name="COMMONSEQ",sequenceName="COMMON_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="COMMONSEQ")
基本配置
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
public Integer getId() {
return this.id;
}
这样hibernate自动生成一个名叫hibernate_sequence的sequence
SQL> select * from USER_SEQUENCES;
hibernate使用sequence的后台动作:
下面是一个save()动作,hibernate 先发出一个 select hibernate_sequence.nextval from dual;
Hibernate:
select
hibernate_sequence.nextval
from
dual
Hibernate:
insert
into
DvdType
(name, id)
values
(?, ?)
1:typeoracle5
用自动创建的hibernate_sequence的缺陷: 会使得多个表共用一个sequnce,造成同一个表序号不连续
TYPE表:
1:TypeExample21
2:TypeExample21
3:TypeExample21
4:TypeExample22
5:TypeExample23
6:TypeExample24
7:TypeExample25
8:TypeExample26
9:TypeExample27
10:TypeExample28
11:TypeExample29
12:TypeExample210
QUALITY表
13:Qualityoracle5
14:QualityExample21
15:QualityExample22
16:QualityExample23
17:QualityExample24
18:QualityExample25
19:QualityExample26
20:QualityExample27
21:QualityExample28
22:QualityExample29
23:QualityExample210
所以建议,还是为每个表定义具体的sequence name
自定义sequence
@Entity
@SequenceGenerator(name="TypeSEQ",sequenceName="TypeSEQ_DB")
public class DvdType implements java.io.Serializable {
@Id
//@GeneratedValue
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TypeSEQ")
@Entity
@SequenceGenerator(name="QualitySEQ",sequenceName="QualitySEQ_DB")
public class QualityType implements java.io.Serializable {
@Id
//@GeneratedValue
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="QualitySEQ")
00:07:46,437 INFO [STDOUT] Hibernate:
select
TypeSEQ_DB.nextval
from
dual
00:08:52,437 INFO [STDOUT] Hibernate:
select
QualitySEQ_DB.nextval
from
dual
hibernate的sequence ,生成的id,事务间缺省是50 increment
现象:
hibernate自动生成的sequence,在oracle下看,increment_by还是1
SQL> select * from USER_SEQUENCES;
SEQUENCE_NAME MIN_VALUE MAX_VALUE INCREMENT_BY C O CACHE_SIZE LAST_NUMBER
------------------------------ ---------- ---------- ------------ - - ---------- -----------
SEQUENCE_DVD_TABLE_1 1 1.0000E+27 1 N N 0 1511
USERSEQ_DB 1 1.0000E+27 1 N N 20 1
GROUPSEQ_DB 1 1.0000E+27 1 N N 20 21
但通过hibernate/JPA进行save/persist()操作,ID却是increment +50
SQL> insert into USERGROUP(ID,NAME) values(GROUPSEQ_DB.nextval,'group6');
1 row created.
SQL> select * from usergroup;
ID NAME
---------- --------------------------------------------------
200 group1
250 group1
300 group3
350 group4
400 group5
9 group6 //这是手工insert的,上面5条记录是hibernate persist的
6 rows selected.
SQL> select GROUPSEQ_DB.nextval from dual;
NEXTVAL
----------
10
原因:
1.hibernate 对sequence参数以自己为准,不读oracle的参数
2.hibernate increment缺省就是50,大概跟 hibernate集群应用有关
解决:hibernate提供了allocationSize参数来设
@Entity
@SequenceGenerator(name="GroupSEQ",sequenceName="GroupSEQ_DB",allocationSize=1)
public class UserGroup {
SQL> select * from usergroup;
ID NAME
---------- --------------------------------------------------
200 group1
250 group1
300 group3
350 group4
400 group5
11 group8 这两条是用hibernate新存的
12 group9
9 group6