本文介绍了Hibernate使用constraintviolationexception进行批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我批量更新大量对象,想要忽略任何重复的对象。
这是什么最好的方法?
我的理解是,如果抛出 ConstrainViolationException
,批次中的所有其他对象将 / strong>。
<$>
解决方案 p $ p>
private void saveBatch(){
StatelessSession session = sessionFactory.openStatelessSession();
事务tx = session.beginTransaction();
try {
for(Object t:batchList){
session.insert(t);
}
tx.commit();
} catch(ConstraintViolationException e){
log.info(批量复制...单独保存);
tx.rollback();
session.close();
saveIndividually();
return;
}
session.close();
batchList.clear();
}
private void saveIndividually(){
StatelessSession session = sessionFactory.openStatelessSession();
for(Object t:batchList){
Transaction tx = session.beginTransaction();
session.insert(t);
try {
tx.commit();
} catch(ConstraintViolationException e){
tx.rollback();
log.warn(Ignoring duplicate:+ t);
}
}
session.close();
batchList.clear();
}
I'm updating a very large number of objects in batches and want to ignore any duplicates.What is the best way of doing this?
My understanding is that if a ConstrainViolationException
is thrown all the other objects in the batch will NOT be persisted.
解决方案
This was my solution:
private void saveBatch() {
StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();
try {
for (Object t : batchList) {
session.insert(t);
}
tx.commit();
} catch (ConstraintViolationException e) {
log.info("Duplicate in batch...save individually");
tx.rollback();
session.close();
saveIndividually();
return;
}
session.close();
batchList.clear();
}
private void saveIndividually() {
StatelessSession session = sessionFactory.openStatelessSession();
for (Object t : batchList) {
Transaction tx = session.beginTransaction();
session.insert(t);
try {
tx.commit();
} catch (ConstraintViolationException e) {
tx.rollback();
log.warn("Ignoring duplicate: " + t);
}
}
session.close();
batchList.clear();
}
这篇关于Hibernate使用constraintviolationexception进行批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-11 05:06