import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.util.concurrent.Callable;
@Service public class TransactionUtil {
private static Logger log = LoggerFactory.getLogger(TransactionUtil.class);
@Autowired private DataSourceTransactionManager dataSourceTransactionManager;
public <T> T doTransaction(Callable<T> job, Runnable rollback) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = dataSourceTransactionManager.getTransaction(def); try { T t = job.call(); dataSourceTransactionManager.commit(status); return t; } catch (Exception e) { dataSourceTransactionManager.rollback(status); if (rollback != null) { rollback.run(); } log.error(e.getMessage(), e); throw new RuntimeException(e); } }
public <T> T doTransaction(Callable<T> job) { return doTransaction(job, null); }
public TransactionStatus begin() { return getTransactionStatus(TransactionDefinition.PROPAGATION_REQUIRED); }
public TransactionStatus beginNew() { return getTransactionStatus(TransactionDefinition.PROPAGATION_REQUIRES_NEW); }
public void commit(TransactionStatus status) { dataSourceTransactionManager.commit(status); }
public void rollback(TransactionStatus status) { dataSourceTransactionManager.rollback(status); }
private TransactionStatus getTransactionStatus(int propagationRequiresNew) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(propagationRequiresNew); TransactionStatus status = dataSourceTransactionManager.getTransaction(def); return status; }
public static void executeAfterCommit(Runnable runnable) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { runnable.run(); } }); }else{ runnable.run(); } }
}
|