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.
在使用Spring、JPA和Hibernate时,遇到PersistenceException时,开发者通常希望捕获异常并返回错误信息,而不是向上抛出。然而,当事务因异常被标记为rollbackOnly时,直接捕获并尝试不重新抛出会导致问题。解决这个问题的方法是将持久化逻辑移到单独的DAO类中,让服务类处理PersistenceException,从而避免事务回滚失败。
3734

被折叠的 条评论
为什么被折叠?



