我正在尝试使用Hibernate(首次涉足数据库)并且在选择使用saveOrUpdate还是Save.Update时感到困惑。我有一个目的地POJO类及其其他属性,需要与Destination实体一起更新。我正在接收一个XML文件进行导入,并使用以下代码更新/保存目的地实体及其属性类。
try{
getSessionFactory().getCurrentSession().beginTransaction();
getSessionFactory().getCurrentSession().saveOrUpdate(entity);
getSessionFactory().getCurrentSession().getTransaction().commit();
}
catch(Exception e){
getSessionFactory().getCurrentSession().getTransaction().rollback();
}
finally{
getSessionFactory().close();
}
一切都运行正常,直到我使用相同的会话实例。但是,当我使用相同的 XML 文件更新目标 PO 的某些属性时,它会给出以下错误。
SEVERE: Duplicate entry 'MNLI' for key 'DESTINATIONID'
9 Jan, 2011 4:58:11 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2242)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
我正在使用UUID作为Destination表的主键,并且在目标表中我有一个唯一的目标ID。但是我可以理解,在第二种情况下,Hibernate无法找到是否已经存在相同目标的条目,并尝试执行插入语句而不是更新语句。
一种可能的解决方案是我可以使用目标ID来检查是否已经存在给定ID的目标,并根据结果发出保存或更新命令。 我的问题是,是否有其他更好的方法来实现这一点?
提前感谢。