当MYSQL设置AUTOCOMMIT = 0时,Mybatis sqlSession.com不起作用

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

我正在使用springboot + mybatis + MYSQL(innodb)

当我设置MYSQL autocommit = 0,并在我的代码中执行事务。我发现交易没有提交。以下是我的代码:

数据源:

spring.datasource.url=jdbc:mysql://localhost:3306/zzzz?characterEncoding=utf8&useSSL=false
spring.datasource.username=xxxx
spring.datasource.password=yyyy
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Mybatis事​​务配置:

@Configuration
@EnableTransactionManagement
public class MyBatisConfiguration {

    @Autowired private DataSource dataSource;

    @Bean @Primary
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
}

我的服务做交易:

@Service
public class AlohaService {

    @Autowired private SqlSessionFactory sqlSessionFactory;

    public void customizedSqlSessionInsert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserRoleMapper userRoleMapper = sqlSession.getMapper(UserRoleMapper.class);
        try {
            userRoleMapper.insert(new UserRole(0, "RRRRR", "ADMIN"));
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }
}

执行customizedSqlSessionInsert方法后,我发现select记录不包含新行RRRR,ADMIN,有趣的是我在MySQL GUI Tool上运行COMMIT命令后,记录出现在MySQL中。

为什么sqlSession.commit();不起作用?谁能帮我?

transactions commit mybatis
1个回答
0
投票

spring-mybatis用于mybatis-spring集成(并且它由spring-boot使用)时,会话上的提交/回滚方法实际上是无操作方法,因为事务由spring管理。那就是spring知道何时开始和完成事务以及如何完成事务(例如,如果抛出异常事务被回滚等)。

与事务相关的所有操作都由org.apache.ibatis.transaction.Transaction的实现处理,SpringManagedTransaction在mybatis-spring的默认配置中是SpringManagedTransaction

这是来自qazxswpoi javadoc:

如果Spring的事务处理处于活动状态,它将禁止所有提交/回滚/关闭调用,假设Spring事务管理器将完成这项工作。

© www.soinside.com 2019 - 2024. All rights reserved.