简体   繁体   English

Spring 3应用程序中的Hibernate @SequenceGenerator问题

[英]Issue with Hibernate @SequenceGenerator in Spring 3 application

we have deployed Spring 3 + Hibernate application on 2 load balancing servers. 我们已经在2个负载平衡服务器上部署了Spring 3 + Hibernate应用程序。

After 50 insertions into the Database, hibernate is not calling the DB sequence nextval, it continuously incrementing the count. 在数据库中插入50次后,休眠状态不会调用nextval数据库序列,它会不断增加计数。 And due to this, the sequence values from both the servers are overlapping and I am getting "Unique Constraint Violation" exception. 由于这个原因,两个服务器的序列值重叠,并且出现“唯一约束违规”异常。

Eg Say, first time the sequence values from both the servers are 100 and 150 respectively. 例如,第一次,两个服务器的序列值分别为100和150。 When the sequence of first instance reaches 149, it is supposed to call seq.nextVal. 当第一个实例的序列达到149时,应该调用seq.nextVal。 But since it is not doing so and continuously incrementing the seq value to 150 which is used by other instance and it is failing. 但是由于它没有这样做,所以将seq值连续增加到150,这被其他实例使用,并且失败了。 default allocationSize: 50 默认分配大小:50

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUSTOMER_ID_SEQ")
@SequenceGenerator(name = "CUSTOMER_ID_SEQ", sequenceName = "CUSTOMER_SEQ")
@Column(name = "CUST_ID", unique = true, nullable = false)
public long getCustId() {
return custId;
}

Thanks in advance. 提前致谢。

If you're using load-balancers, but the DB is shared between the instances, you cannot cache the sequences' values. 如果使用负载均衡器,但实例之间共享数据库,则无法缓存序列的值。

You have to ask for the next sequence value each time you insert into DB. 每次插入DB时,都需要询问下一个序列值。 And each insert has to be inside a transaction. 并且每个插入都必须在事务内。 Hibernate, (by default) has allocationSize = 50, so to fix your problem, you have to explicitly set it to 1. Hibernate(默认情况下)的分配大小= 50,因此要解决您的问题,必须将其显式设置为1。

 @SequenceGenerator(allocationSize=1 ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM