Spring + MyBatis 框架下处理数据库异常

一、概述

使用JDBC API时,很多操作都要声明抛出java.sql.SQLException异常,通常情况下是要制定异常处理策略。而Spring的JDBC模块为我们提供了一套异常处理机制,这套异常系统的基类是DataAccessException,它是RuntimeException的一种类型,那么就不用强制去捕捉异常了,Spring的异常体系如下: 

查了一下资料发现MyBatis有自己特殊的处理异常方式。Mapper这一层说白了写的还是DataAccessObject数据访问对象,异常自然也就是DataAccessException数据访问异常了。

二、示例代码

1、首先Mapper抛出异常

public interface ISignInMapper {
    int insertInToSignIn( int userId,String signInTime) throws SQLException;
}

2、Service层继续向上抛出

public interface ISignInService {
    boolean insert(int userId,String signInTime)throws DataAccessException;
}
public class SignInServiceImpl implements ISignInService{
    @Override
    public boolean insert(int userId,String SignInTime) throws DataAccessException{
        int rows = this.signInDao.insertInToSignIn(userId,SignInTime);
        return rows > 0 ? true : false;
    }
}

3、Controller中捕获并处理

try{
    bool = signInService.insert(userId,signInTime);
}catch (DataAccessException e){
    final Throwable cause = e.getCause();
    if(cause instanceof MySQLIntegrityConstraintViolationException){
        response.getWriter().write(mapper.writeValueAsString("Duplicate entry"));
    }else {
        response.getWriter().write(mapper.writeValueAsString(bool?"success":"error"));
    }
    response.getWriter().close();
}

catch块中```MySQLIntegrityConstraintViolationException是违反完整性约束异常,可以根据实际情况换为其他异常类型

 
 

三、Spring的DataAccessException说明

   Spring的DAO框架没有抛出与特定技术相关的异常,例如SQLException或HibernateException,抛出的异常都是与特定技术无关的org.springframework.dao.DataAccessException类的子类,避免系统与某种特殊的持久层实现耦合在一起。DataAccessException是RuntimeException,是一个无须检测的异常,不要求代码去处理这类异常,遵循了Spring的一般理念:异常检测会使代码到处是不相关的catch或throws语句,使代码杂乱无章;并且NestedRuntimeException的子类,是可以通过NestedRuntimeException的getCause()方法获得导致该异常的另一个异常。Spring的异常分类有:

Spring的DAO异常层次是如此的细致缜密,服务对象能够精确地选择需要捕获哪些异常,捕获的异常对用户更有用的信息,哪些异常可以让她继续在调用堆栈中向上传递。

原文地址:https://www.cnblogs.com/caoweixiong/p/11181188.html