Mybatis不鼓励捕捉异常,但在某些特定场景下需要捕捉,这个时候通过try catch是捕捉不到的,mybatis有自己的处理方式,它把异常映射成了DataAccessException,那么我们需要抛出异常并捕捉。

service中抛出异常

  1. @Transactional(readOnly=false)
  2. public int save(BaseDepartment department) throws DataAccessException{
  3. return departmentDao.insert(department);
  4. }

controller中捕获异常并进行处理

  1. try {
  2. if (departmentService.save(department) > 0) {
  3. body.setReason("成功");
  4. body.setResultFlag(1);
  5. } else {
  6. body.setReason("失败");
  7. body.setResultFlag(801);
  8. }
  9. } catch (DataAccessException e) {
  10. body.setReason("保存失败:部门名称已存在!");
  11. body.setResultFlag(8012);
  12. }

 

转载于:https://my.oschina.net/penghaozhong/blog/729319