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;
spring framework runtime}
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){
}else {
}
}
catch块中```MySQLIntegrityConstraintViolationException是违反完整性约束异常,可以根据实际情况换为其他异常类型
三、Spring的DataAccessException说明
Spring的DAO框架没有抛出与特定技术相关的异常,例如SQLException或HibernateException,抛出的异常都是与特定技术⽆关的org.springframework.dao.DataAccessException类的⼦类,避免系统与某种
特殊的持久层实现耦合在⼀起。DataAccessException是RuntimeException,是⼀个⽆须检测的异常,不要求代码去处理这类异常,遵循了Spring的⼀般理念:异常检测会使代码到处是不相关的catch或throws语句,使代码杂乱⽆章;并且NestedRuntimeException的⼦类,是可以通过NestedRuntimeException的getCause()⽅法获得导致该异常的另⼀个异常。Spring的异常分类有:
Spring的DAO异常层次是如此的细致缜密,服务对象能够精确地选择需要捕获哪些异常,捕获的异常对⽤户更有⽤的信息,哪些异常可以让她继续在调⽤堆栈中向上传递。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。