以下代码尝试使用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方法的信息,我知道它的作用.
最佳答案