import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.function.Supplier;
/**
* @author ll
* @description 编程式事务工具类
* @date 2022/1/17 20:50
*/
@Slf4j
@Component
public class TransactionUtil {
@Resource
private PlatformTransactionManager transactionManager;
public boolean transactional(Supplier<Boolean> supplier) {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
Boolean res = supplier.get();
if (Objects.isNull(res) || !res) {
transactionManager.rollback(status);
return false;
} else {
transactionManager.commit(status);
return true;
}
} catch (Exception e) {
log.error("编程式事务业务异常回滚", e);
transactionManager.rollback(status);
return false;
}
}
}
11-22
340
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-02
981
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)