在JPA + Spring中异常后回滚事务 [英] Roll back transaction after exception in JPA + Spring
问题描述
我在下面使用Spring和JPA和HIbernate。当抛出PersistenceException时,我想捕获它并返回错误消息,以便它不会传播给调用者。
@Transactional
public String save(Object bean){
String error = null;
尝试{
EntityManager entityManager = getEntityManager(); (int i = 0,n = entities.size(); i< n; i ++){
entityManager.merge(entities.get(i));
。
catch(PersistenceException e){
error = e.getMessage();
}
返回错误;
}
但是我得到一个异常,指出 javax.persistence .RollbackException:标记为rollbackOnly的事务。
我得到事务需要在异常后回滚,但当我捕获异常并且不想重新抛出时,如何回滚它它看起来没有办法回滚由Spring ORM管理的失败的事务处理。问题中显示的代码是一个服务类。将其持久化例程提取到单独的DAO类并使服务类句柄 PersistenceExceptions
取得了诀窍。
I'm using Spring and JPA with HIbernate underneath. When a PersistenceException is thrown, I want to catch it and return the error message so that it is not propagated up to the caller.
@Transactional
public String save(Object bean) {
String error = null;
try {
EntityManager entityManager = getEntityManager();
for (int i = 0, n = entities.size(); i < n; i ++) {
entityManager.merge(entities.get(i));
}
}
catch (PersistenceException e) {
error = e.getMessage();
}
return error;
}
But I get an exception saying that javax.persistence.RollbackException: Transaction marked as rollbackOnly.
I get that the transaction needs to be rolled back after an exception but how do I roll it back when I've catched the exception and do not want to re-throw it?
It appears that there is no way to roll back a failed transaction managed by Spring ORM. The code shown in the question is a service class. Extracting its persistence routine to a separate DAO class and having the service class handle PersistenceExceptions
did the trick.
这篇关于在JPA + Spring中异常后回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!