package common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

@Component
public class TransactionUtils {

    @Autowired
    @Qualifier(value = "jdbcTransactionManager")
    private DataSourceTransactionManager jdbcTransactionManager;

    // 开启事务
    public TransactionStatus begin() {
        TransactionStatus transaction = jdbcTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return transaction;
    }

    // 提交事务
    public void commit(TransactionStatus transaction) {
        jdbcTransactionManager.commit(transaction);
    }

    // 回滚事务
    public void rollback(TransactionStatus transaction) {
        jdbcTransactionManager.rollback(transaction);
    }
}
