Hint
This article is generated by AI translation.
Annotation-Based Transactions
Declaratively control transactions by marking methods or classes with the @Transactional annotation.
Basic usage
import net.hasor.dbvisitor.transaction.Transactional;
public class TxExample {
@Transactional
public void exampleMethod() {
...
}
}
Annotation Attributes
@Transactional supports the following attributes:
| Attribute | Type | Default | Description |
|---|---|---|---|
propagation | Propagation | REQUIRED | Transaction propagation behavior |
isolation | Isolation | DEFAULT | Transaction isolation level |
readOnly | boolean | false | Whether the transaction is read-only |
noRollbackFor | Class<? extends Throwable>[] | {} | Exception types that should not trigger rollback |
noRollbackForClassName | String[] | {} | Exception class names that should not trigger rollback |
Specify propagation and isolation
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED)
public void exampleMethod() {
...
}
Specify no-rollback exceptions
@Transactional(noRollbackFor = { IllegalArgumentException.class })
public void exampleMethod() {
...
}
Enabling Annotation-Based Transactions
The @Transactional annotation requires an interceptor to take effect. Depending on the framework you use:
Framework Integration
- Spring transaction annotations: see details
- Solon transaction annotations: see details
Raw Application
Without framework support, you can use TransactionHelper.support() to manually create a proxy object that enables annotation-based transactions.
Enable annotation-based transactions via proxy
DataSource dataSource = ...;
TxExample txExample = new TxExample();
// Create a proxy for txExample that automatically handles @Transactional
txExample = TransactionHelper.support(txExample, dataSource);
// Methods on the proxy will have automatic transaction management
txExample.exampleMethod();
Note
TransactionHelper.support() accepts varargs DataSource..., allowing you to bind transaction interceptors for multiple data sources at once.