package com.jy.framework.utils;

import cn.hutool.extra.spring.SpringUtil;
import lombok.NonNull;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.function.Supplier;

public class TransactionUtil {

    private final static TransactionTemplate transactionTemplate = SpringUtil.getBean(TransactionTemplate.class);

    public static void execute(Runnable runnable) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(@NonNull TransactionStatus status) {
                try {
                    runnable.run();
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    public static <T> T execute(Supplier<T> supplier) {
        return transactionTemplate.execute(status -> {
            try {
                return supplier.get();
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
    }

}
