Class TxTry
Try-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 Try<V> captures failure as a return value, no exception
escapes, and the transaction commits even on failure — silently persisting partial writes.
TxTry solves this by inspecting the returned Try: if
Try.isFailure() is true, the transaction is marked rollback-only before the
template commits.
Quick start
@Service
public class ReportService {
private final TxTry tx;
public ReportService(TxTry tx) { this.tx = tx; }
public Try<Report> generate(ReportRequest req) {
return tx.execute(() ->
Try.of(() -> reportRepo.save(build(req)))
.map(r -> { auditLog.record(r); return r; })
);
}
}
Wire this bean by declaring a PlatformTransactionManager in your Spring context.
Spring Boot auto-configures one for every registered DataSource.
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionTxTry(org.springframework.transaction.PlatformTransactionManager txManager) Creates aTxTrybacked by the given transaction manager. -
Method Summary
-
Constructor Details
-
TxTry
public TxTry(org.springframework.transaction.PlatformTransactionManager txManager) Creates aTxTrybacked 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
Try.isSuccess(). The transaction is rolled back when:- the action returns
Try.isFailure(), or - the action throws an unchecked exception (propagates to the caller).
- Type Parameters:
V- the success value type- Parameters:
action- the transactional action; must not benulland must not returnnull- Returns:
- the
Tryreturned byaction - Throws:
NullPointerException- ifactionisnullor returnsnull
- the action returns
-
execute
public <V> Try<V> execute(org.springframework.transaction.TransactionDefinition def, Supplier<Try<V>> 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); Try<List<Report>> reports = tx.execute(readOnly, reportRepo::findAll);- Type Parameters:
V- the success value type- Parameters:
def- the transaction definition; must not benullaction- the transactional action; must not benulland must not returnnull- Returns:
- the
Tryreturned byaction - Throws:
NullPointerException- if any argument isnullor ifactionreturnsnull
-