java – 在插入失败后恢复Hibernate会话状态

以下代码尝试使用Spring Hibernate将Item对象插入到db中. Item具有Integer id字段作为主键,以及受独特约束限制的名称列(简化示例).
我知道项目的id为空(项目是暂时的)但是由于名称字段上的唯一约束,插入可能仍然失败.

try {
  getHibernateTemplate().save(myItem);
  getHibernateTemplate().flush(); // exception thrown here if the name is not unique
}
catch (DataIntegrityViolationException e) {
  Item itemFromDb = (Item) getHibernateTemplate()
    .find("from Item item where item.name = ?",myItem.getName()).get(0);
  //
  // copy some properties from myItem to itemFromDb
  //
  getHibernateTemplate.update (itemFromDb)
}

我需要这个代码在多个项目的循环中运行,所有这些都在一个事务中,这就是为什么我试图在插入失败时发出更新的原因.

但是,在插入失败后,hibernate会话处于奇怪的状态,当我发出select语句从db获取项时,抛出原始异常.

我尝试在插入失败后使用session.evict(),但无济于事.任何的想法?

这是我在选择失败后在控制台中看到的内容. Hibernate在select语句上失败,但仍然打印有关前一个insert语句的信息.

WARN  [http-8080-1] hibernate.util.JDBCExceptionReporter (JDBCExceptionReporter.java:77) - sql Error: 2627,sqlState: 23000
ERROR [http-8080-1] hibernate.util.JDBCExceptionReporter (JDBCExceptionReporter.java:78) - Violation of UNIQUE KEY constraint 'unq_Item_name'. Cannot insert duplicate key in object 'items'.
ERROR [http-8080-1] event.def.AbstractFlushingEventListener (AbstractFlushingEventListener.java:301) - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not insert: [com.sample.Item]
    at org.hibernate.exception.sqlStateConverter.convert(sqlStateConverter.java:71)

附:请不要告诉我有关hibernate的saveOrUpdate方法的信息,我知道它的作用.

最佳答案
一旦抛出数据库异常,Hibernate就不保证会话的任何内容.你应该回滚.如果我理解Bozho的建议,他说你应该先从名称栏中读取,以确保插入不会失败.我感觉合理.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...