springboot事务工具类
时间: 2023-11-27 09:47:45 浏览: 79
以下是一个简单的SpringBoot事务工具类的示例代码:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
@Component
public class TransactionUtils {
@Autowired
private PlatformTransactionManager transactionManager;
public <T> T executeInTransaction(TransactionCallback<T> callback) {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
try {
T result = callback.doInTransaction();
transactionManager.commit(transactionStatus);
return result;
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
throw e;
}
}
public interface TransactionCallback<T> {
T doInTransaction();
}
}
```
这个工具类中的`executeInTransaction`方法接受一个`TransactionCallback`参数,该参数是一个函数式接口,用于执行需要在事务中执行的代码。如果执行成功,则提交事务,否则回滚事务。
使用该工具类的示例代码如下:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private TransactionUtils transactionUtils;
public void transferMoney(int fromUserId, int toUserId, double amount) {
transactionUtils.executeInTransaction(() -> {
User fromUser = userRepository.findById(fromUserId).orElseThrow(() -> new RuntimeException("User not found"));
User toUser = userRepository.findById(toUserId).orElseThrow(() -> new RuntimeException("User not found"));
fromUser.setBalance(fromUser.getBalance() - amount);
toUser.setBalance(toUser.getBalance() + amount);
userRepository.save(fromUser);
userRepository.save(toUser);
return null;
});
}
}
```
在上面的示例代码中,`transferMoney`方法需要在事务中执行,因此我们将其放在了`executeInTransaction`方法中,并将其作为参数传递给了`TransactionUtils`工具类。
阅读全文