package org.wcs.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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;
import org.wcs.utils.function.RunnableThrowEx;

@Slf4j
@Component
@RequiredArgsConstructor
public class AppDataBaseTransUtils {

    private final PlatformTransactionManager transactionManager;

    /**
     * 执行一个事务方法
     * @param baseTran 事务类
     * @return 执行结果
     */
    public boolean useTran(RunnableThrowEx baseTran) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            baseTran.run();
            transactionManager.commit(status);
            return true;
        } catch (Exception e) {
            transactionManager.rollback(status);
            log.error("事务执行失败", e);
            return false;
        }
    }
}
