springboot整合mybatis 集成事务 注解方式
1. pom文件相关依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
2.application.properties配置jdbc相关参数
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql:///xxx
3.注入数据源
@Configuration
public class DataSourceConfig {
private String driverClassName = "com.mysql.jdbc.Driver";
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driverClassName);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(username);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
}
4.mybatis相关配置 集成事务
@Configuration
public class MyBatisConfig implements TransactionManagementConfigurer{
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(false);
configuration.setLogImpl(StdOutImpl.class);
bean.setConfiguration(configuration);
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
在pom文件中mybatis-spring的版本在1.2.x之后不再自动装配SqlSessionFactory 和SqlSessionTemplate ,如果没有手动注入的话,启动项目会报错,找不到这两个。
5.扫描mapper接口注解
在主配置类上添加注解 @MapperScan(“xxx.mapper”)
接下来只需要在service实现类中添加@Transactional注解,即可开始事务支持
也可以在其方法上添加注解 @Transactional(rollbackFor = RuntimeException.class)