Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

java - Hibernate generates negative id values when using a sequence

I have a class with the following definition:

@Id
@SequenceGenerator(name = "SEQ_ACE_WORKERS_QUEUE_STATS_ID", sequenceName = "SEQ_ACE_WORKERS_QUEUE_STATS_ID", allocationSize = 500)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ACE_WORKERS_QUEUE_STATS_ID")
@Column(name = "ID")
private long Id;

When we ran it on Jboss 4.2.3 it worked fine and generated the proper ID's (starting from 1000+)

Now we moved to jboss 7.1.1 and it generates negative ID's! (starting from -498 and going up)

Any idea why this might happen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The new behaviour is the followings:

AllocationSize is a range of primary key values reserved for Hibernate. And the select seq.nextval from dual will be done only after hibernate consumed this range of primary keys.

So you must declare the same value on both allocationSize (Hibernate) and sequence increment by (DB)

When explicitly set allocationSize=500, e.g. on Oracle

create sequence SEQ_ACE_WORKERS_QUEUE_STATS_ID
       MINVALUE 1 
       MAXVALUE 999999999999999999999999999 
       START WITH 1
       INCREMENT BY 500 
       NOCACHE 
       NOCYCLE;

Otherwise, you'll notice negative values or constraint errors raised from your DB because of primary key collisions.

When the app server is restarted, you'll notice the 'jump' between the latest primary key allocated, and the 'newly' sequence number selected at restart.

Final comment: default value is 50. So if you don't specify allocationSize on the Hibernate side, you must declare increment by 50 on the DB side.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...