当前位置:   article > 正文

springboot管理事务_springboot 事务maven

springboot 事务maven

Managing Transactions

1.目标

建立一个简单的JDBC应用,设置数据库的事务而不用写JDBC代码。

2.代码

pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.4.3</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>managing-transactions</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>managing-transactions</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>mysql</groupId>
  22. <artifactId>mysql-connector-java</artifactId>
  23. <version>8.0.13</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-data-jdbc</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-test</artifactId>
  32. <scope>test</scope>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-maven-plugin</artifactId>
  40. </plugin>
  41. </plugins>
  42. </build>
  43. </project>

 写一个基于JDBC服务,将学生姓名登记到系统中。

新建src/main/java/com/example/managingtransactions/BookingService.java

  1. package com.example.managingtransactions;
  2. import java.util.List;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.jdbc.core.JdbcTemplate;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.transaction.annotation.Transactional;
  8. @Component
  9. public class BookingService {
  10. private final static Logger logger = LoggerFactory.getLogger(BookingService.class);
  11. private final JdbcTemplate jdbcTemplate;
  12. public BookingService(JdbcTemplate jdbcTemplate) {
  13. this.jdbcTemplate = jdbcTemplate;
  14. }
  15. @Transactional
  16. public void book(String... persons) {
  17. for (String person : persons) {
  18. logger.info("Booking " + person + " in a seat...");
  19. jdbcTemplate.update("insert into BOOKINGS(FIRST_NAME) values (?)", person);
  20. }
  21. }
  22. public List<String> findAllBookings() {
  23. return jdbcTemplate.query("select FIRST_NAME from BOOKINGS",
  24. (rs, rowNum) -> rs.getString("FIRST_NAME"));
  25. }
  26. }

 这里有一个book方法,使用JdbcTemple通过循环将每个学生插入到BOOKINGS表中。该方法使用@Transactional标记,意思是整个执行过程中,有任何失败都会回滚到之前的状态。也就是说,如果任何一个学生添加失败,就不会有学生添加到BOOKINGS表中。

新建src/main/java/com/example/managingtransactions/ManagingTransactionsApplication.java

  1. package com.example.managingtransactions;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class ManagingTransactionsApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(ManagingTransactionsApplication.class, args);
  8. }
  9. }

@SpringBootApplication,是简单的使用方法它包括:

@Configuration,将一个类作为bean定义的源代码添加到应用上下文中。

@EnableAutoConfiguration,告诉SpringBoot启动的时候将classpath路径下的、其他的bean和各种配置添加进来。例如,如果spring-webmvc在classpath中,那么该标记将应用作为一个web应用激活关键的行为,比如说建立DispatcherServlet。

@ComponentScan,告诉Spring在com/exampe下查找其他components、configurations和services,让他们能够找到controllers。

main方法使用SpringApplication.run()启动一个应用,你可能发现没有任何XML文件,没有web.xml文件。该web应用是100%纯的java代码。

该应用没有任何的配置。Spring Boot监测到spring-jdbc和h2在classpath中,然后会自动创建一个DataSource和一个JdbcTemplate。以上这些由DataSourceTransactionManager进行管理。

3.运行测试

使用CommandLineRunner一样可以达到这样的效果。

 新建src/main/java/com/example/managingtransactions/AppRunner.java

  1. package com.example.managingtransactions;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.boot.CommandLineRunner;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.util.Assert;
  7. @Component
  8. class AppRunner implements CommandLineRunner {
  9. private final static Logger logger = LoggerFactory.getLogger(AppRunner.class);
  10. private final BookingService bookingService;
  11. public AppRunner(BookingService bookingService) {
  12. this.bookingService = bookingService;
  13. }
  14. @Override
  15. public void run(String... args) throws Exception {
  16. bookingService.book("Alice", "Bob", "Carol");
  17. Assert.isTrue(bookingService.findAllBookings().size() == 3,
  18. "First booking should work with no problem");
  19. logger.info("Alice, Bob and Carol have been booked");
  20. try {
  21. bookingService.book("Chris", "Samuel");
  22. } catch (RuntimeException e) {
  23. logger.info("v--- The following exception is expect because 'Samuel' is too " +
  24. "big for the DB ---v");
  25. logger.error(e.getMessage());
  26. }
  27. for (String person : bookingService.findAllBookings()) {
  28. logger.info("So far, " + person + " is booked.");
  29. }
  30. logger.info("You shouldn't see Chris or Samuel. Samuel violated DB constraints, " +
  31. "and Chris was rolled back in the same TX");
  32. Assert.isTrue(bookingService.findAllBookings().size() == 3,
  33. "'Samuel' should have triggered a rollback");
  34. try {
  35. bookingService.book("Buddy", null);
  36. } catch (RuntimeException e) {
  37. logger.info("v--- The following exception is expect because null is not " +
  38. "valid for the DB ---v");
  39. logger.error(e.getMessage());
  40. }
  41. for (String person : bookingService.findAllBookings()) {
  42. logger.info("So far, " + person + " is booked.");
  43. }
  44. logger.info("You shouldn't see Buddy or null. null violated DB constraints, and " +
  45. "Buddy was rolled back in the same TX");
  46. Assert.isTrue(bookingService.findAllBookings().size() == 3,
  47. "'null' should have triggered a rollback");
  48. }
  49. }

通过命令行执行

mvn spring-boot:run

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/995337
推荐阅读
相关标签