Template Mode
Hint
This article is generated by AI translation.
Template transactions follow this general pattern:
try {
txManager.begin(propagation, isolation);
...
txManager.commit();
} catch (Throwable e) {
txManager.rollBack();
throw e;
}
Example usage:
TransactionTemplate template = ...
Object result = template.execute(new TransactionCallback<Object>() {
@Override
public Object doTransaction(TransactionStatus tranStatus) throws Throwable {
...
return null;
}
});
Java 8 style
Object result = template.execute(tranStatus -> {
return ...;
});
Run a block in a transaction and ignore the return value
template.execute((TransactionCallbackWithoutResult) tranStatus -> {
...
});
Rolling back
There are two ways to roll back when using the template:
- Throw an exception.
- Mark the transaction for rollback via
rollBackorreadOnlywithout throwing.
Mark rollback without throwing
Object result = template.execute(new TransactionCallback<Object>() {
public Object doTransaction(TransactionStatus tranStatus) {
tranStatus.setReadOnly();
// 或
tranStatus.setRollback();
return ...;
}
});
Obtain a transaction manager
From a DataSource
DataSource dataSource = ...
TransactionManager txManager = TransactionHelper.txManager(dataSource);
Via dependency injection
public class TxExample {
// @Inject < Guice、Solon 和 Hasor
// @Resource or @Autowired < Spring
private TransactionManager txManager;
...
}
For DI usage, see the framework-specific docs
- Spring-based projects: see details
- Solon-based projects: see details
- In Hasor and Guice you can inject with
@Inject