springboot jpa手动事务

创建springboot项目

搭建最简单的SpringBoot项目_Steven-Russell的博客-CSDN博客

引入jpa和数据库依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.28</version>
    <scope>provided</scope>
</dependency>

创建实体类

@Data
@Entity
@Table(name = "tbl_user")
public class User {

    @Id
    @Column
    @GeneratedValue
    private int id;

    @Column
    private String name;

    @Column
    private String addr;

    @UpdateTimestamp
    @Column
    private Date updateTime;
}

创建Repository

public interface UserRepository extends CrudRepository<User, Integer> {
     @Transactional
     @Modifying
     int deleteAllByNameIn(@Param(value = "nameList") List<String> nameList);
}

创建controller 并且注入 事务管理器和Repository

注意:需要注入 PlatformTransactionManager

创建数据

构建异常
@GetMapping(value = "transactional")
public String transactionalUser() {
    DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
    transDefinition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus transStatus = transactionManager.getTransaction(transDefinition);
    try {
        deleteUser4Transactional();
        addUser4Transactional();
        transactionManager.commit(transStatus);
    } catch (Exception e) {
        e.printStackTrace();
        transactionManager.rollback(transStatus);
    }

    return "success";
}

private void addUser4Transactional() {
    int i = 1;
    int ans = i/0;
    User user = new User();
    user.setName("addUser4TransactionalName");
    user.setAddr("chongqing");
    userRepository.save(user);
}

private void deleteUser4Transactional() {
    List<String> nameList = new ArrayList<String>(){{
        add("aaa");
        add("ccc");
    }};
    int ans = userRepository.deleteAllByNameIn(nameList);
    System.out.println("deleteUser4Transactional ans : " + ans);
}

调用接口(预期回滚)

如下所示,数据没有变化

删除事务管理器

构建异常

调用接口(异常之前的操作被正常提交,并没有被回滚)

发现数据已经被删除,但是异常之后的添加操作并没有生效提交