注意:
1、数据表引擎需要设置为innoDb (myIsam不支持事务)
2、一定要抛出异常,不然不会自动回滚
1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
<exclusions>
<exclusion>
<groupId>com.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
2 开启事务管理器
package com.timi.t1.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
3 使用事务
@Transactional
public R syncField(@RequestBody JSONObject jsonObject){
try{
storyMapper.update(updateWrapper);
MybatisBatch<StoryChangeRecord> mybatisBatch = new MybatisBatch<>(sqlSessionFactory, recordList);
MybatisBatch.Method<StoryChangeRecord> method = new MybatisBatch.Method<>(StoryChangeRecordMapper.class);
mybatisBatch.execute(method.insert());
}catch (Exception exception){
throw new GlobalException("同步失败:" + exception.getMessage());
}
}