Java Hibernate JPA 约束违规和事务已激活
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23875206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate JPA constraint violation and Transaction already active
提问by K.Ariche
I have a table with the field 'nom' with the unique constraint and when I test to insert a value of this field that already exists in the table the org.hibernate.exception.ConstraintViolationExceptionis thrown. Then after all my persisting I get a Transaction already activeException.
我有一个带有唯一约束的字段 'nom' 的表,当我测试插入表中已存在的该字段的值时,抛出org.hibernate.exception.ConstraintViolationException。然后在我坚持之后,我得到了一个事务已经激活的异常。
this is my persisting method in a Dao class
这是我在 Dao 类中的持久化方法
public void persist(E entity) throws Exception {
EntityTransaction tr=entityManager.getTransaction() ;
tr.begin();
entityManager.persist(entity);
tr.commit();
}
and here the code where I catch the exception
这里是我捕获异常的代码
try {
rd.persist(r);
} catch (Exception e) {
e.printStackTrace();
}
How Can I solve this Transaction problem ?
我怎样才能解决这个交易问题?
采纳答案by ganaraj
Instead of explicitly opening the transaction you could allow the framework to handle the transaction (like in spring you can use the @transactional). But if not it looks like the code has a begin and a commit in case it is successful, try adding a tr.rollback() in the persist method using a finally (or you could even check whether the transaction is still active using the tr.isActive() method.
您可以允许框架处理事务,而不是显式打开事务(就像在 spring 中,您可以使用 @transactional)。但如果不是,它看起来像代码有一个开始和一个提交,以防它成功,请尝试使用 finally 在持久方法中添加一个 tr.rollback() (或者您甚至可以使用 tr 检查事务是否仍然处于活动状态.isActive() 方法。
回答by Laster Liang
There is no need to do anything with Transaction, because it is handled by Spring.
不需要对 Transaction 做任何事情,因为它是由 Spring 处理的。
I met "Transaction already active". Though I think what caused it is different with your problem, I think my answer should help someone.
我遇到了“交易已经激活”。虽然我认为导致它的原因与您的问题不同,但我认为我的回答应该对某人有所帮助。
For example:
例如:
// Transaction handled by Spring
Session session = sessionFactory.getCurrentSession();
...
return;
------------------------------------------------------------
// Transaction handled by yourself
Session session = sessionFactory.openSession();
Transcation tr = session.beginTransaction();
...
tr.commit();
session.close();
return;