Mybatis中捕獲不到了MySQLIntegrityConstraintViolationException

Mybatis不鼓勵捕捉異常,但在某些特定場景下須要捕捉,這個時候經過try catch是捕捉不到的,mybatis有本身的處理方式,它把異常映射成了DataAccessException,那麼咱們須要拋出異常並捕捉。java

service中拋出異常mybatis

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

controller中捕獲異常並進行處理code

try {
			if (departmentService.save(department) > 0) {
				body.setReason("成功");
				body.setResultFlag(1);
			} else {
				body.setReason("失敗");
				body.setResultFlag(801);
			}
		} catch (DataAccessException e) {
			body.setReason("保存失敗:部門名稱已存在!");
			body.setResultFlag(8012);
		}
相關文章
相關標籤/搜索