我正在使用Spring 3.2和Hibernate 3.6进行工作,有人能解释一下如何在Spring MVC和Hibernate中处理异常...我只是分享一些示例代码。
控制器层
public Integer saveEployee(HttpServletRequest req, HttpServletResponse res){
Employee empObj = new Employee();
empObj.setName(req.getParameter("empName"));
......................
......................
Integer empId = materService.saveEmployee(empObj);
return empId;
}
服务层
public Integer saveEmployee(Employee empObj){
return masterDao.saveEmployee(empObj);
}
数据访问层
public Integer saveEmployee(Employee empObj){
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Integer empId = session.save(empObj);
tx.commit();
session.close();
return empId;
}
现在假设在保存empObj时,DAO层发生了任何异常,例如数据库崩溃、连接失败或其他类型的Hibernate异常,如
ConstraintViolationException
或IntegrityConstraintViolationException
等。如果存在Java异常(例如
NullPointerException
或任何用户定义的异常)需要在控制器层进行处理。
因此,如何同时在控制器、服务和DAO层处理异常是什么最佳实践或应该注意的呢?
@ExceptionHandler(value={ConstraintViolationException.class, IntegrityConstraintViolationException.class,...})
进行标记。 - thoitbk