diff --git a/spring-tx/src/main/java/org/springframework/transaction/support/TransactionOperations.java b/spring-tx/src/main/java/org/springframework/transaction/support/TransactionOperations.java index f8c8847af0..ffec5fb708 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/support/TransactionOperations.java +++ b/spring-tx/src/main/java/org/springframework/transaction/support/TransactionOperations.java @@ -44,6 +44,28 @@ public interface TransactionOperations { @Nullable T execute(TransactionCallback action) throws TransactionException; + /** + * Execute the action specified by the given {@link Runnable} within a transaction. + *

If you need to return an object from the callback or access the + * {@link org.springframework.transaction.TransactionStatus} from within the callback, + * use {@link #execute(TransactionCallback)} instead. + *

This variant is analogous to using a {@link TransactionCallbackWithoutResult} + * but with a simplified signature for common cases - and conveniently usable with + * Java 8 lambda expressions. + * @param action the Runnable that specifies the transactional action + * @throws TransactionException in case of initialization, rollback, or system errors + * @throws RuntimeException if thrown by the Runnable + * @since 5.2 + * @see #execute(TransactionCallback) + * @see TransactionCallbackWithoutResult + */ + default void execute(Runnable action) throws TransactionException { + execute(status -> { + action.run(); + return null; + }); + } + /** * Return an implementation of the {@code TransactionOperations} interface which diff --git a/spring-tx/src/main/java/org/springframework/transaction/support/WithoutTransactionOperations.java b/spring-tx/src/main/java/org/springframework/transaction/support/WithoutTransactionOperations.java index 52a289ed5f..a106f0f250 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/support/WithoutTransactionOperations.java +++ b/spring-tx/src/main/java/org/springframework/transaction/support/WithoutTransactionOperations.java @@ -31,13 +31,20 @@ final class WithoutTransactionOperations implements TransactionOperations { static final WithoutTransactionOperations INSTANCE = new WithoutTransactionOperations(); + private WithoutTransactionOperations() { } + @Override @Nullable public T execute(TransactionCallback action) throws TransactionException { return action.doInTransaction(new SimpleTransactionStatus(false)); } + @Override + public void execute(Runnable action) throws TransactionException { + action.run(); + } + }