在Spring Boot中,实现事务有以下几种方法:
@Transactional
注解在需要事务管理的方法上,Spring Boot会自动开启事务、提交事务或回滚事务。@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}
}
@EnableTransactionManagement
注解启用事务管理,并在配置文件中配置事务管理器。@Configuration
@EnableTransactionManagement
public class TransactionConfig {
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void saveUser(User user) {
userRepository.save(user);
}
}
TransactionTemplate
类手动控制事务的开始、提交和回滚。@Service
public class UserService {
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private UserRepository userRepository;
public void saveUser(User user) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
userRepository.save(user);
}
});
}
}
以上是常用的三种实现事务的方法,根据具体情况选择适合的方法。