mysql getconnection 如何关闭连接_mybatis 如何关闭connection

public class SqlSessionTemplate implements SqlSession, DisposableBean { //这里实现了sqlSession,一般可以把SqlSessionTemplate当作sqlsession来使用

publicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,

PersistenceExceptionTranslator exceptionTranslator) {

notNull(sqlSessionFactory,"Property 'sqlSessionFactory' is required");

notNull(executorType,"Property 'executorType' is required");this.sqlSessionFactory =sqlSessionFactory;this.executorType =executorType;this.exceptionTranslator =exceptionTranslator;this.sqlSessionProxy =(SqlSession) newProxyInstance(

SqlSessionFactory.class.getClassLoader(),new Class[] { SqlSession.class},new SqlSessionInterceptor());//在构造方法中,我们看到sqlSessionProxy这个代理类是通过内部类SqlSessionInterceptor来生成

}/*** {@inheritDoc}*/@Overridepublic T selectOne(String statement, Object parameter) {return this.sqlSessionProxy.selectOne(statement, parameter);

}/*** {@inheritDoc}*/@Overridepublic MapselectMap(String statement, String mapKey) {return this.sqlSessionProxy. selectMap(statement, mapKey); //而且sql执行大部分都是通过代理类来调用,所以关键就是这个内部类

}private class SqlSessionInterceptor implementsInvocationHandler { //这个就是内部类,实现了InvocationHandler接口,因为要通过代理方式完成关闭连接

@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throwsThrowable {

SqlSession sqlSession=getSqlSession(

SqlSessionTemplate.this.sqlSessionFactory,

SqlSessionTemplate.this.executorType,

SqlSessionTemplate.this.exceptionTranslator);try{

Object result=method.invoke(sqlSession, args); //这里执行被代理的方法if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {//force commit even on non-dirty sessions because some databases require//a commit/rollback before calling close()

sqlSession.commit(true);

}returnresult;

}catch(Throwable t) {

Throwable unwrapped=unwrapThrowable(t);if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceofPersistenceException) {//release the connection to avoid a deadlock if the translator is no loaded. See issue #22

closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); //可以看到如果报错在catch语句中会关闭sqlsession,也就是我们刚刚分析的一系列类最终关闭Connection

sqlSession = null;

Throwable translated= SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);if (translated != null) {

unwrapped=translated;

}

}throwunwrapped;

}finally{if (sqlSession != null) {

closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);//如果不报错,finally也关闭sqlsession

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值