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

被折叠的 条评论
为什么被折叠?



