Spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement 开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可。

关于事务管理器,不管是JPA还是JDBC等都实现自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依赖,框架会默认注入 DataSourceTransactionManager 实例。如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。

你可以在启动类中添加如下方法,Debug测试,就能知道自动注入的是 PlatformTransactionManager 接口的哪个实现类。

@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication {

    @Bean
    public Object testBean(PlatformTransactionManager platformTransactionManager){
        System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());
        return new Object();
    }

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

这些SpringBoot为我们自动做了,这些对我们并不透明,如果你项目做的比较大,添加的持久化依赖比较多,我们还是会选择人为的指定使用哪个事务管理器。 

 

代码如下:

@EnableTransactionManagement
@SpringBootApplication
public class ProfiledemoApplication {

    // 其中 dataSource 框架会自动为我们注入
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public Object testBean(PlatformTransactionManager platformTransactionManager) {
        System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());
        return new Object();
    }

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

Service中,被 @Transactional 注解的方法,将支持事务。如果注解在类上,则整个类的所有方法都默认支持事务。


1. 使用properties文件配置springboot默认数据源

这种方式十分简单,只用在application.properties文件中配置数据库连接属性即可。

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xunwu
spring.datasource.username=wali
spring.datasource.password=wali

这里有个注意事项:

springboot 2.0+中使用jdbc-url配置数据库URL1.5中使用url,不然会导致一个错误。jdbcUrl is required with driverClassName

运行测试方法,查看springboot是否自动配置数据源

@RunWith(SpringRunner.class)
@SpringBootTest
public class MonsterlanApplicationTests {
   @Autowired
   DataSourceProperties dataSourceProperties;

   @Autowired
   ApplicationContext applicationContext;

   @Test
   public void contextLoads() {
      // 获取配置的数据源
      DataSource dataSource = applicationContext.getBean(DataSource.class);
      // 查看配置数据源信息
      System.out.println(dataSource);
      System.out.println(dataSource.getClass().getName());
      System.out.println(dataSourceProperties);
      //执行SQL,输出查到的数据
      JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
      List<?> resultList = jdbcTemplate.queryForList("select * from test");
      System.out.println("===>>>>>>>>>>>" + JSON.toJSONString(resultList));
   }
}

通过输出信息,我们可以看到我们通过properties文件配置数据源十分方便,springboot会直接在容器中构建一个dataSource供我们使用。

2. 通过注解配置数据源DataSource
通过注解配置datasource,这个比使用springboot默认的数据源配置要更灵活一些,还可以根据项目需求配置多个不同的DataSource(如果项目使用到多个数据库)

创建一个配置类DataSourceConfig

@Configuration
public class DataSourceConfig {

    @Bean(name = "myDataSource")
    @Qualifier("myDataSource")
    @ConfigurationProperties(prefix="spring.datasource.other")
    public DataSource getMyDataSource(){
        return DataSourceBuilder.create().build();
    }
}

通过Junit测试数据源

@RunWith(SpringRunner.class)
@SpringBootTest
public class MonsterlanApplicationTests {
   @Autowired
   DataSourceProperties dataSourceProperties;

   @Autowired
   ApplicationContext applicationContext;

   @Resource(name = "myDataSource")
   private DataSource myDataSource;

   @Test
   public void contextLoads() {
      //执行SQL,输出查到的数据
      JdbcTemplate jdbcTemplate = new JdbcTemplate(myDataSource);
      List<?> resultList = jdbcTemplate.queryForList("select * from menu");
      System.out.println("===>>>>>>>>>>>" + JSON.toJSONString(resultList));
   }
}

这样我们就能使用数据源进行数据库操作了。

相关maven依赖配置:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- alibaba JSON工具 -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.4</version>
</dependency>