Class TxResult
Result-returning action inside a managed transaction,
automatically rolling back when the result represents a failure.
Spring's @Transactional rolls back only when an unchecked exception escapes the
annotated method. Since Result<V,E> captures failure as a return value, no exception
escapes, and the transaction commits even on error — silently persisting partial writes.
TxResult solves this by inspecting the returned Result: if
Result.isError() is true, the transaction is marked rollback-only before the
template commits.
Quick start
@Service
public class OrderService {
private final TxResult tx;
public OrderService(TxResult tx) { this.tx = tx; }
public Result<Order, OrderError> createOrder(OrderRequest req) {
return tx.execute(() ->
validate(req)
.flatMap(this::persistOrder)
.flatMap(this::notifyInventory)
);
}
}
Wire this bean by declaring a PlatformTransactionManager in your Spring context.
Spring Boot auto-configures one for every registered DataSource.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionTxResult(org.springframework.transaction.PlatformTransactionManager txManager) Creates aTxResultbacked by the given transaction manager. -
Method Summary
-
Constructor Details
-
TxResult
public TxResult(org.springframework.transaction.PlatformTransactionManager txManager) Creates aTxResultbacked by the given transaction manager.- Parameters:
txManager- the transaction manager; must not benull- Throws:
NullPointerException- iftxManagerisnull
-
-
Method Details
-
execute
Executesactioninside a transaction using the defaultTransactionDefinition(propagation REQUIRED, isolation DEFAULT).The transaction commits if the action returns
Result.isOk(). The transaction is rolled back when:- the action returns
Result.isError(), or - the action throws an unchecked exception (propagates to the caller).
- Type Parameters:
V- the success value typeE- the error type- Parameters:
action- the transactional action; must not benulland must not returnnull- Returns:
- the
Resultreturned byaction - Throws:
NullPointerException- ifactionisnullor returnsnull
- the action returns
-
execute
public <V,E> Result<V,E> execute(org.springframework.transaction.TransactionDefinition def, Supplier<Result<V, E>> action) Executesactioninside a transaction configured bydef.Use this overload when you need explicit control over propagation, isolation level, timeout, or read-only flag:
var readOnly = new DefaultTransactionDefinition(); readOnly.setReadOnly(true); Result<List<Order>, String> orders = tx.execute(readOnly, orderRepo::findAll);- Type Parameters:
V- the success value typeE- the error type- Parameters:
def- the transaction definition; must not benullaction- the transactional action; must not benulland must not returnnull- Returns:
- the
Resultreturned byaction - Throws:
NullPointerException- if any argument isnullor ifactionreturnsnull
-