[英]Hibernate session.flush() causes ORA-00001: unique constraint
I have this method that inserts thousands of records to the database using hibernate. 我有这种方法,可以使用休眠方式将数千条记录插入数据库。
According to this article , flushing and clearing helps to release some precious memory, and the code below does this every 100 records. 根据本文 ,刷新和清除有助于释放一些宝贵的内存,下面的代码每100条记录执行一次。 But the problem:
但是问题是:
ORA-00001: unique constraint (OWNER.FOO_TABLE_PK) violated ORA-00001:违反了唯一约束(OWNER.FOO_TABLE_PK)
always occurs when the code session.flush() is invoked, which is after the 100th save (the PK of FOO_TABLE is a simple long id). 总是在调用代码session.flush()时发生,这是在第100次保存之后(FOO_TABLE的PK是一个简单的长id)。 I have tried removing the session.flush() and session.clear() entirely and added session.evict(obj) after the session.save() and that fixed the problem.
我试图完全删除session.flush()和session.clear(),并在session.save()之后添加session.evict(obj),从而解决了问题。 I am not sure if it is a good practice though.
我不确定这是否是一个好习惯。
Would you guys have any idea why session.flush() causes a unique constraint error? 你们知道为什么session.flush()会导致唯一约束错误吗? Flushing and clearing at regular intervals are heavily suggested, but I am not sure if I am using them properly.
强烈建议定期进行冲洗和清除,但是我不确定是否正确使用它们。 Any inputs will be appreciated.
任何输入将不胜感激。 Thanks!
谢谢!
@Override
@Transactional
public void bulkSave(List<Foo> objList) {
Session session = sessionFactory.getCurrentSession();
if (objList != null) {
if (!objList.isEmpty()) {
int counter = 0;
for (Foo obj : objList) {
session.save(objList);
counter++;
if ((counter % 100) == 0) {
session.flush();
session.clear();
}
}
}
}
}
Well flushing causes the state to be flushed through to the database. 良好的刷新会导致状态刷新到数据库。 If there's a primary key violation, there's something wrong with how you're assigning the primary key for your object.
如果存在主键冲突,则为对象分配主键的方式有问题。
After a more in-depth investigation, I have determined that this is not the fault of Hibernate. 经过更深入的调查,我确定这不是Hibernate的错。 Hibernate uses the number provided by the ID Sequence Generator as primary keys.
Hibernate使用ID序列生成器提供的数字作为主键。 Someone manually uploaded a test data which used IDs not accounted for by the Sequence Generator.
有人手动上传了测试数据,该数据使用了序列生成器未提供的ID。 Eventually when hibernate caught-up, it cannot use the ID provided by the generator because the ID already exists in the Database, hence the Unique Constraint violation after the session.flush().
最终,在陷入休眠状态时,它无法使用生成器提供的ID,因为该ID已存在于数据库中,因此session.flush()之后违反了唯一约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.