[英]Exception Handling with Spring's @Transactional
I'm developing a web app with Spring MVC and hibernate for persistence. 我正在使用Spring MVC和hibernate开发一个用于持久性的Web应用程序。 Given my DAO where GenericDao has a SessionFactory member attribute:
鉴于我的DAO,GenericDao有一个SessionFactory成员属性:
@Repository
public class Dao extends GenericDao {
public void save(Object o) {
getCurrentSession().save(o);
}
}
And a Service class 和服务类
@Service
public class MyService {
@Autowired
Dao dao;
@Transactional
public void save(Object o) {
dao.save(o);
}
}
I want to inform my user if a persistence exception occurs (constraint, duplicate, etc). 我想通知我的用户是否发生持久性异常(约束,重复等)。 As far as I know, the
@Transactional
annotation only works if the exception bubbles up and the transaction manager rolls back so I shouldn't be handling the exception in that method. 据我所知,@
@Transactional
注释仅在异常冒泡并且事务管理器回滚时才有效,因此我不应该在该方法中处理异常。 Where and how should I catch an exception that would've happened in the DAO so that I can present it to my user, either directly or wrapped in my own exception? 我应该在哪里以及如何捕获DAO中发生的异常,以便我可以将其直接呈现给我的用户,或者包含在我自己的异常中?
I want to use spring's transaction support. 我想使用spring的事务支持。
Spring provides Exception Handlers. Spring提供了异常处理程序。
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers
So you could have something like this in your controller to handle a ConstraintViolationException 所以你可以在你的控制器中有这样的东西来处理ConstraintViolationException
@ExceptionHandler(ConstraintViolationException.class)
public ModelAndView handleConstraintViolationException(IOException ex, Command command, HttpServletRequest request)
{
return new ModelAndView("ConstraintViolationExceptionView");
}
After chasing around the issue for a while, I solved this by using an exception handler (as described in another answer) and the rollbackFor
property of the @Transactional
annotation: 在追逐问题一段时间后,我通过使用异常处理程序(如另一个答案中所述)和
@Transactional
注释的rollbackFor
属性解决了这个问题:
@Transactional(rollbackFor = Exception.class)
My exception handler is still called and writes the response accordingly, but the transaction is rolled back. 我的异常处理程序仍然被调用并相应地写入响应,但事务被回滚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.