dawdler-tx-core
Module Introduction
Local transaction core module. It provides a transaction manager with a transaction API that is essentially aligned with Spring (propagation behavior / isolation level / timeout / read-only; the default rollback rule is the opposite of Spring, see below), manages thread-level connection context, and provides a transaction synchronization callback system plus cross-thread transaction context propagation (executor / virtual threads). It is the underlying dependency of dawdler-db-core (transaction aspect / read-write splitting / sharding routing), dawdler-dao-core and dawdler-mybatis-core. Pure JDBC implementation, depending only on slf4j-api.
1. Adding the dependency in pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-tx-core</artifactId>
Usually there is no need to add it explicitly; using dawdler-db-plug or dawdler-dao-plug brings this module in transitively.
2. The DBTransaction annotation
@DBTransaction is applied to implementation methods of a Service. Note that propagation across remote calls is not supported (calling a server service from another server service is generally not recommended either). Participating propagation behaviors (REQUIRED/NESTED) are only guaranteed to join the same physical transaction when they map to the same data source and the same shard; across databases/shards the inner transaction commits independently. See dawdler-db-core for details.
public @interface DBTransaction {
MODE mode() default MODE.deferToConfig;
// MODE.forceReadOnWrite, // Force reads onto the write connection. With read-write splitting, use this when business logic that depends on freshly inserted data cannot rely on real-time replica data.
// MODE.deferToConfig, // Follow the annotation definition of this method; this is the default and supports read-write splitting.
// MODE.readOnly // Only a read connection is passed in
READ_CONFIG readConfig() default READ_CONFIG.idem;
// READ_CONFIG.idem, // Same as the definition of the outer layer
// READ_CONFIG.deferToConfig // Follow the annotation definition of this method
Class<? extends Throwable>[] noRollbackFor() default {};//The specified exceptions do not roll back. Note this means NO rollback. By default any Throwable (including checked exceptions) rolls back, the opposite of Spring, where only RuntimeException/Error roll back by default
Propagation propagation() default Propagation.REQUIRED;
// REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED),// Support the current transaction; create a new one if none exists.
// SUPPORTS(TransactionDefinition.PROPAGATION_SUPPORTS),// Support the current transaction; execute non-transactionally if none exists.
// MANDATORY(TransactionDefinition.PROPAGATION_MANDATORY),// Support the current transaction; throw an exception if none exists.
// REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW),// Create a new transaction; suspend the current one if it exists.
// NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED),// Execute non-transactionally; suspend the current transaction if it exists.
// NEVER(TransactionDefinition.PROPAGATION_NEVER),// Execute non-transactionally; throw an exception if a transaction exists.
// NESTED(TransactionDefinition.PROPAGATION_NESTED);// If a transaction exists, execute within a nested transaction. If none exists, behave like PROPAGATION_REQUIRED.
Isolation isolation() default Isolation.DEFAULT;//Database isolation level. Takes effect only when a new transaction is started; when joining an existing transaction, declaring an isolation level different from the current transaction throws an exception
// DEFAULT(TransactionDefinition.TRANSACTION_DEFAULT), //Default isolation level
// NONE(TransactionDefinition.TRANSACTION_NONE), //Transactions unsupported (the original isolation level of the connection returned by the driver may be this value; after the transaction ends it is precisely restored to the original value)
// READ_UNCOMMITTED(TransactionDefinition.TRANSACTION_READ_UNCOMMITTED),//Read uncommitted
// READ_COMMITTED(TransactionDefinition.TRANSACTION_READ_COMMITTED),//Read committed, the Oracle default
// REPEATABLE_READ(TransactionDefinition.TRANSACTION_REPEATABLE_READ),// Repeatable read, the MySQL default
// SERIALIZABLE(TransactionDefinition.TRANSACTION_SERIALIZABLE);//Serializable
int timeOut() default 0;//Transaction timeout (seconds); values <= 0 disable it. When enabled, the remaining time is computed from the transaction start time and applied as each statement's queryTimeout. On expiry a TransactionTimedOutException is thrown when acquiring a connection (checked on both the read and write paths) or when creating a statement, and the transaction rolls back. Applies to both read-write and read-only (mode=readOnly) paths; when joining an existing transaction the inner declaration has no effect and the outer deadline applies
/* The logic is as follows:
* if (queryTimeout == null || queryTimeout == 0 || transactionTimeout < queryTimeout) {
* statement.setQueryTimeout(transactionTimeout);
* }
* mysql driver code:
* public int getQueryTimeout() throws SQLException {
* synchronized (checkClosed().getConnectionMutex()) {
* return getTimeoutInMillis() / 1000;
* }
* }
*/
boolean readOnly() default false;//Read-only transaction. At transaction start setReadOnly(true) is executed on the connection as a driver hint (e.g. MySQL read-only optimization) and restored afterwards. Note this is a hint, not an enforcement; it takes effect only when a new transaction is started and is ignored when joining an existing one
}
The default rollback rule is the opposite of Spring: any Throwable thrown by a business method (including checked exceptions) rolls back by default, and exceptions to exclude are specified via noRollbackFor. Spring, by default, rolls back only RuntimeException and Error and commits on checked exceptions (which are added via rollbackFor). When migrating from Spring to dawdler, note that the rollback semantics for checked exceptions are reversed.
3. Thread-level connection context
LocalConnectionFactory maintains thread-level read and write connections plus the transaction timeout context. The dao layer and the mybatis layer obtain the current context connections via getReadConnection()/getWriteConnection(), so business code does not need to pass a Connection parameter.
Cross-data-source nested transactions (services annotated with @DBTransaction that use different data sources calling each other) are implemented by saving/restoring the thread's write-connection context with the transaction state, so the outer transaction can continue using its own connection after the inner transaction ends.
3.1 Connection occupancy model
Both read and write connections are materialized lazily: the context holds connection holders, and the physical connection is checked out only on first use. Therefore "transaction started" and "physical connection occupied" are two separate things (the WriteConnectionHolder.transactionActive flag is independent of the connection field).
- Starting a transaction does not occupy a connection:
doBegin(starting a new physical transaction) only sets the transaction flag and does not check out the write connection at that point; the write connection and itssetAutoCommit(false)are applied together on the firstgetWriteConnection(). Methods that only use the read path therefore do not occupy a write connection from the pool. - Configurations that need the connection ready still materialize it: a non-
DEFAULTisolation(the isolation level must be set on the new transaction's connection),readOnly=true(the read-only hint must be set) andNESTED(a savepoint must be created) all check out the write connection duringdoBegin. - Ending a transaction does not fetch an extra connection:
cancelTransactiononly restoresautoCommiton an already materialized connection and never checks out one just to restore it. - Commit/rollback do not fetch an extra connection:
TransactionObject.commit/rollbackonly act on a materialized connection (peekConnection()peeks without triggering a checkout); if the transaction never obtained a write connection, commit/rollback is a no-op. - Nested-frame detection does not depend on the connection: whether an active transaction exists is decided by a flag, so a holder whose connection is not materialized is still recognized by a nested @DBTransaction frame as an existing transaction (otherwise the inner call would wrongly start a new physical transaction and reset the outer transaction's autoCommit).
Connection occupancy of a single @DBTransaction method:
| Scenario | Write connection | Read connection |
|---|---|---|
mode=readOnly | 0 | 1 (lazy) |
Read-only semantics without mode=readOnly | 1 (lazy) | 1 (lazy, from the read data source) |
| Mixed read and write | 1 | 1 (from the read data source) |
mode=forceReadOnWrite | 1 | 0 (reads reuse the write connection) |
| Write path only within the transaction | 1 | 0 |
Note that with the default mode=deferToConfig the read connection comes from the read data source and is a separate physical connection from the write connection, so a "mixed read and write" method occupies two connections at once. This also means reads inside the transaction cannot see the transaction's own uncommitted writes (replication lag is directly visible); use mode=forceReadOnWrite when you need read-your-own-writes.
4. Cross-thread transaction context propagation (TransactionContext)
Transaction state is kept in a ThreadLocal and is invisible outside the thread boundary: work derived from a @DBTransaction method into an executor or a virtual thread will throw TransactionRequiredException when obtaining a connection, and if it performs its own read-write routing it will silently read from the replica (not seeing the outer transaction's uncommitted data). TransactionContext offers two propagation modes:
// 1. Explicit executor propagation: capture the calling thread's transaction state; the worker thread restores it and joins the outer transaction
TransactionContext snapshot = TransactionContext.capture();
executor.submit(TransactionContext.wrap(() -> dao.update(entity)));
// 2. Decorate the executor; every submit automatically captures the submitting thread's transaction state
Executor propagated = TransactionContext.wrap(executor);
// 3. Manual install/restore with try-with-resources
try (AutoCloseable ignored = snapshot.open()) {
dao.update(entity);
}
// 4. Structured-concurrency child virtual threads inherit automatically (inside a transactional method, no wrapping needed)
try (var scope = StructuredTaskScope.open()) {
var subtask = scope.fork(() -> dao.query(id));
scope.join();
}
Propagation semantics:
- Database operations on the worker thread join the outer transaction (same physical connection, same physical transaction); read-write routing and the timeout deadline apply as well, and the remaining transaction timeout also applies to statements in the child thread.
- Transaction synchronization callbacks registered within the worker thread belong to the outer physical transaction and fire with the outer commit/rollback; if the worker thread starts a participating transaction and marks it rollbackOnly, the outer commit throws UnexpectedRollbackException and the whole transaction rolls back.
- Nested transactions inside a child thread (e.g. REQUIRES_NEW) suspend/restore only that child thread's own binding table and do not corrupt the initiating thread's transaction state.
- The worker thread's state is cleaned up automatically when the task ends, so pooled threads do not leak stale bindings.
Automatic inheritance mechanism: the transaction aspect binds the transaction snapshot with ScopedValue, a finalized API in JDK 25, inside the @DBTransaction method body; child virtual threads forked by StructuredTaskScope inherit it automatically the first time they access the database. Plain new Thread / Thread.ofVirtual().start() do not inherit ScopedValue bindings and still require explicit wrap propagation.
Thread-safety contract: a JDBC Connection is not thread-safe, and the snapshot propagates participation in the transaction, not a copy of it. The capturing thread must not perform database operations while the snapshot is installed on another thread (hand-off semantics, like JTA's suspend/resume across threads); concurrent subtasks using the same transactional connection at the same time is undefined behavior. Derived work must complete before the outer transaction commits/rolls back (structured concurrency's join guarantees this; in the executor case you must wait for the future to complete before returning from the transactional method).
5. Transaction synchronization callbacks
Modeled on Spring's transaction synchronization mechanism, used for side effects that should take effect only after a successful transaction (e.g. writing the cache/sending a message after commit, cleaning up resources after rollback).
public interface TransactionSynchronization {
int STATUS_COMMITTED = 0;// afterCompletion status: committed
int STATUS_ROLLED_BACK = 1;// afterCompletion status: rolled back
int STATUS_UNKNOWN = 2;// afterCompletion status: completion status unknown (the commit or rollback process itself failed)
default void beforeCommit(boolean readOnly) {}// Callback before commit (commit path only); throwing RuntimeException causes a rollback
default void beforeCompletion() {}// Callback before completion, after beforeCommit (commit path only); throwing RuntimeException causes a rollback
default void afterCommit() {}// Callback after a successful commit; thrown exceptions are only logged, not rethrown
default void afterCompletion(int status) {}// Callback after completion (fired for both commit and rollback); thrown exceptions are only logged, not rethrown
}
Register via TransactionSynchronizationManager:
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
// Execute after the transaction commits
}
});
Rules:
- The lifecycle of the callback list matches the physical transaction; callbacks are registered on the physical transaction active on the current thread.
- Callbacks registered in a code block that joins an existing transaction (REQUIRED/NESTED savepoint) belong to the outer physical transaction and fire with the outer commit/rollback.
- Cross-data-source nesting and REQUIRES_NEW each hold their own independent list; the outer list is restored after the inner transaction ends.
- While NOT_SUPPORTED is suspending, there is no active list and registering throws IllegalStateException; registering with no transaction also throws IllegalStateException (call isSynchronizationActive() first to check).
- The callback list is backed by CopyOnWriteArrayList: a worker thread installed via TransactionContext and the transaction-owning thread access the same list concurrently, so registering callbacks from multiple threads is safe and the snapshot read at commit/rollback needs no locking.
before*callbacks fire before transaction cleanup (the transactional connection can still be used);after*callbacks fire after transaction cleanup (connection returned / context restored), so the transactional database connection cannot be used inside them.- A RuntimeException thrown by beforeCommit/beforeCompletion causes the transaction to roll back, and afterCompletion receives STATUS_UNKNOWN; when the commit/rollback process itself fails, STATUS_UNKNOWN is received as well.
Differences from Spring's implementation (exception-handling semantics, compared with Spring 5.x/6.x):
- beforeCommit: the same; a RuntimeException causes the transaction to roll back.
- beforeCompletion: Spring catches Throwable per callback and only logs it without rethrowing; this module does not catch it, and the exception propagates and causes a rollback — rolling back conservatively when a pre-completion callback fails is safer.
- afterCommit: Spring does not catch it, so the exception propagates to the caller of commit() (the transaction is still considered committed and does not roll back), and one callback throwing interrupts the remaining afterCommit callbacks; this module catches Throwable per callback and only logs it at ERROR level without rethrowing, and one failing callback does not prevent the following callbacks from running — an infrastructure failure in the post-commit phase (e.g. writing the cache) should not be misreported to the business caller as a business failure.
- afterCompletion: the same; exceptions thrown are caught per callback as Throwable and only logged without rethrowing.
@Cacheable/@CachePut in dawdler-cache-core are already wired in: a put inside a transaction is deferred until afterCommit, and discarded when the transaction rolls back, so the cache does not retain data that was rolled back.
6. Package structure
- club.dawdler.core.tx.transaction Transaction manager and connection context (TransactionContext provides cross-thread propagation)
- club.dawdler.core.tx.annotation DBTransaction/Propagation/Isolation annotations
- club.dawdler.core.tx.exception Transaction exceptions