package org.jeecg.config.mybatis.update;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.function.Supplier;

/**
 * @description: 事务工具类
 * @author: niugeng
 * @create: 2023-01-07 16:00
 **/
@Slf4j
@Configuration
@RequiredArgsConstructor
public class TransactionUtil {
    private final TransactionTemplate template;
    /** * 手动执行事务, 简化事务覆盖面 * * @param task 执行任务，并自定义返回值 * @return U 自定义返回对象 */
    public <U> U execute(Supplier<U> task) {
        return template.execute(transactionStatus -> {
            try {
                return task.get();
            } catch (Exception e) {
                // 自动捕捉异常，回滚
                log.error("任务异常, 回归事务: ", e);
                transactionStatus.setRollbackOnly();
                throw e;
            }
        });
    }
}
