Skip to content

Commit 2c33c11

Browse files
committed
Introduce TransactionOperations.execute(Runnable) convenience method
Closes gh-23250
1 parent 7f33344 commit 2c33c11

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

spring-tx/src/main/java/org/springframework/transaction/support/TransactionOperations.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,28 @@ public interface TransactionOperations {
4444
@Nullable
4545
<T> T execute(TransactionCallback<T> action) throws TransactionException;
4646

47+
/**
48+
* Execute the action specified by the given {@link Runnable} within a transaction.
49+
* <p>If you need to return an object from the callback or access the
50+
* {@link org.springframework.transaction.TransactionStatus} from within the callback,
51+
* use {@link #execute(TransactionCallback)} instead.
52+
* <p>This variant is analogous to using a {@link TransactionCallbackWithoutResult}
53+
* but with a simplified signature for common cases - and conveniently usable with
54+
* Java 8 lambda expressions.
55+
* @param action the Runnable that specifies the transactional action
56+
* @throws TransactionException in case of initialization, rollback, or system errors
57+
* @throws RuntimeException if thrown by the Runnable
58+
* @since 5.2
59+
* @see #execute(TransactionCallback)
60+
* @see TransactionCallbackWithoutResult
61+
*/
62+
default void execute(Runnable action) throws TransactionException {
63+
execute(status -> {
64+
action.run();
65+
return null;
66+
});
67+
}
68+
4769

4870
/**
4971
* Return an implementation of the {@code TransactionOperations} interface which

spring-tx/src/main/java/org/springframework/transaction/support/WithoutTransactionOperations.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,20 @@ final class WithoutTransactionOperations implements TransactionOperations {
3131

3232
static final WithoutTransactionOperations INSTANCE = new WithoutTransactionOperations();
3333

34+
3435
private WithoutTransactionOperations() {
3536
}
3637

38+
3739
@Override
3840
@Nullable
3941
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
4042
return action.doInTransaction(new SimpleTransactionStatus(false));
4143
}
4244

45+
@Override
46+
public void execute(Runnable action) throws TransactionException {
47+
action.run();
48+
}
49+
4350
}

0 commit comments

Comments
 (0)