Mybatis-Spring事务:当TransactionSynchronizationManager绑定SqlSessionFacotry和SqlSessionHolder时?

问题描述 投票:0回答:0

我是按照代码执行流程看Mybatis如何与Spring配合使用的,到了

SqlSessionInterceptor.invoke(..)
最后执行了
isSqlSessionTransactional(...)
方法来决定是否commit with
SqlSession.commit
。当代码带有
@Transactional
时,
isSqlSessionTransactional(..)
返回 true.

但是什么时候

SqlSessionFactory
SqlSessionHolder
绑定? 我已经在调试模式下运行代码以在
TransactionSynchronizationManager.bindResource
上挂起,但我仍然没有找到绑定
SqlSessionFactory
SqlSessionHolder
绑定。

Mybatis-Spring类SqlSessionInterceptor:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      SqlSession sqlSession = getSqlSession(....);
      try {
        Object result = method.invoke(sqlSession, args);
        if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
          sqlSession.commit(true);
        }
        return result;
      

测试代码:

@Mapper
public interface StuMapper {
    @Update("update stu set name = #{name};")
    void update(String name);
}

@Component
public class TXComponent2 {
    @Resource
    private StuMapper stuMapper;

    @Transactional
    public void m3() throws MyEx {
        stuMapper.update("oooooo");
    }

@SpringBootApplication
public class MybatisDemoApplication implements CommandLineRunner {
    @Autowired
    private TXComponent2 component2;

    public static void main(String[] args) {
        SpringApplication.run(MybatisDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("begin");
        component2.m3();
    }
}
spring spring-boot mybatis spring-mybatis
© www.soinside.com 2019 - 2024. All rights reserved.