这是我在 DAOImpl(Hibernate)中的代码:
@Transactional
public void insert(Cage cage) {
Session session = null;
Transaction tx = null;
try{
session = getHibernateTemplate().getSessionFactory().openSession();
tx = session.beginTransaction();
session.saveOrUpdate(cage);
session.flush();
session.clear();
tx.commit();
}catch(RuntimeException e){
try{
tx.rollback();
}catch(RuntimeException rbe){
rbe.printStackTrace();
System.out.println("Couldn’t roll back transaction");
}
throw e;
}finally{
if(session!=null){
session.close();
}
}
}
当第二次操作数据输入(相同的PK)时出现此问题:
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
最佳答案
根据你的问题
When for the second time operations data entry (Same PK) takes place with this problem : org.hibernate.exception.ConstraintViolationException:
您正尝试插入相同的主键两次。 数据库中的两个条目不能具有相同的主键。
主键必须包含唯一值。 检查此链接 http://www.w3schools.com/sql/sql_primarykey.asp
保持主键唯一,您就不会遇到此异常。 如果您需要该列的重复条目,则不要将其设为主键
自动生成id
@Id @GenerateValue(策略= GenerationType.AUTO) @Column(名称=“\”ID\“”) 私有(private) int id;
关于java - 提交 session 时 hibernate 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37793781/