企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
这里以 JDBC 为例。 <br/> **1. 引入 spring-boot-starter-jdbc** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.33</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> ``` **2. 配置数据库信息`application.yml`** ```yml spring: datasource: username: root password: uhg</flEt3dff url: jdbc:mysql://localhost:3306/common?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver ``` **3. 在接口上或接口方法上标记事务注解`@Transactional`开启事务** ```java public interface PersonService { /** * 标记在接口、接口方法、类及类的方法上都可以开启事务 */ @Transactional void addPerson(Integer num); } @Service @RequiredArgsConstructor public class PersonServiceImpl implements PersonService { final JdbcTemplate jdbcTemplate; @Override public void addPerson() { for (int i = 0; i < 1000; i++) { jdbcTemplate.update("insert into tb_person(id,per_name,age)values(uuid(),?,?)", new Object[]{"zhangsan", 25}); jdbcTemplate.update("insert into tb_student(id,stu_name,age)values(uuid(),?,?)", new Object[]{"李四", 30}); if (i == 600) { throw new RuntimeException("抛出异常了"); } } } } ``` 当`i == 600`抛出异常,查看数据库没有插入任何的数据,这就是事务的作用。它保证了要么全部成功,要么有一个失败就全都失败。 **** 案例代码:https://gitee.com/flymini/codes03/tree/master/learn-stransaction 事务失效的十种场景(转载):https://mp.weixin.qq.com/s/N1Gr181pOX-OeCE12f4OIw