【587、spring的事务怎么用】

58 阅读1分钟

在 Spring 中,可以使用 @Transactional 注解来管理事务。使用 @Transactional 注解可以将一个方法或者类声明为事务性方法,可以配置事务的传播行为、隔离级别、超时时间、回滚规则等属性。

在使用 @Transactional 注解时,需要在 Spring 配置文件中配置事务管理器,如使用 DataSourceTransactionManager 来管理事务,同时需要将 @EnableTransactionManagement 注解添加到 Spring 配置类上启用事务管理功能。

例如,在 Spring Boot 应用中使用 @Transactional 注解,可以按照以下步骤操作:

  1. 在 Maven 中添加 Spring Boot Starter JDBC 和 MySQL 驱动等依赖:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>
  1. 在 application.properties 配置文件中配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  1. 在 Spring 配置类中添加 @EnableTransactionManagement 注解启用事务管理功能:
@Configuration
@EnableTransactionManagement
public class AppConfig {
    // ...
}
  1. 在 Service 层中使用 @Transactional 注解管理事务,例如:
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    @Transactional
    public void transferMoney(String fromUser, String toUser, double amount) {
        User from = userRepository.findByUsername(fromUser);
        User to = userRepository.findByUsername(toUser);
        from.setBalance(from.getBalance() - amount);
        to.setBalance(to.getBalance() + amount);
        userRepository.save(from);
        userRepository.save(to);
    }
}

在上面的例子中,@Transactional 注解被用于 transferMoney 方法上,表示该方法是一个事务性方法。当该方法执行时,如果出现异常,则事务将回滚,保证原来的数据状态不会被修改。如果方法执行成功,则事务将提交,修改将永久保存到数据库中。

需要注意的是,在默认情况下,Spring 的事务管理器只会对 RuntimeException 及其子类的异常进行回滚,对于其他异常不会回滚事务。如果需要对其他异常也进行回滚,则需要使用 @Transactional 注解的 rollbackFor 属性或 noRollbackFor 属性进行配置。