判断当前方法是否存在事务
TransactionSynchronizationManager . isActualTransactionActive ( )
封装工具类
@Slf4j
public class TransactionUtils {
private static final TransactionTemplate transactionTemplate = SpringContextHolder . getBean ( TransactionTemplate . class ) ;
public static void execRunnable ( Runnable runnable) {
transactionTemplate. execute ( new TransactionCallbackWithoutResult ( ) {
@Override
protected void doInTransactionWithoutResult ( @NotNull TransactionStatus status) {
try {
runnable. run ( ) ;
} catch ( Exception e) {
status. setRollbackOnly ( ) ;
log. error ( e. getMessage ( ) , e) ;
throw new RuntimeException ( e) ;
}
}
} ) ;
}
public static < T > T execCallable ( Callable < T > callable) {
SingleObject < T > singleObject = new SingleObject < > ( ) ;
transactionTemplate. execute ( new TransactionCallbackWithoutResult ( ) {
@Override
protected void doInTransactionWithoutResult ( @NotNull TransactionStatus status) {
try {
T t = callable. call ( ) ;
singleObject. setT ( t) ;
} catch ( Exception e) {
status. setRollbackOnly ( ) ;
log. error ( e. getMessage ( ) , e) ;
throw new RuntimeException ( e) ;
}
}
} ) ;
return singleObject. getT ( ) ;
}
}