MyBatis 源码解析SqlSession.getConnection(Connection异常:关闭或者不在Mybatis事务)

本文探讨了MyBatis中SqlSessionTemplate的Connection获取问题,详细解析了内部类SqlSessionInterceptor的工作原理,指出在获取连接时由于delegate的holder为空导致的问题,并提供了一种解决方案,即直接调用SqlSessionUtils的getConnection方法来绕过代理,从而确保Connection的正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从SqlSession的实现类SqlSessionTemplate源码中,看出相关方法被其内部类SqlSessionInterceptor(实现了InvocationHandler)代理

当调用SqlSessionTemplate.getConnection()时,有SqlSessionInterceptor代理执行,从SqlSessionInterceptor源码中看到其invoke方法finally代码块那内容如:

//关闭SqlSession

 

导致获取到的Connection中delegate(委托)的holder(存放事务对象)为空

 

解决方案:

抽离代理,将代理方法SqlSessionInterceptor.invoke中的代码拿出直接使用

SqlSessionTemplate st = (SqlSessionTemplate) getSqlSession();

Connection connection = SqlSessionUtils.getSqlSession(
                st.getSqlSessionFactory(), st.getExecutorType(),
                st.getPersistenceExceptionTranslator()).getConnection();

这样获取到的Connection可以正常使用

转载于:https://www.cnblogs.com/Zhongzz/p/9407639.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值