Strategies
A Transactor.Strategy defines hooks that wrap every execution. The built-in strategies cover common patterns — this page covers customization.
Hook Lifecycle
| Hook | When it runs |
|---|---|
onBegin | Before your code — typically setAutoCommit(false) |
onSuccess | After your code succeeds — typically commit |
onFailure | When an exception is thrown (catch) — receives the connection and the throwable |
onComplete | In all cases (finally) — typically close |
listener | A QueryListener for observability (see Observability) |
Custom Strategies
Build a strategy from scratch using replaceX methods — each one sets a single hook:
- Kotlin
- Java
- Scala
val customStrategy: Strategy =
Strategy.empty()
.replaceOnBegin { conn -> conn.autoCommit = false }
.replaceOnSuccess(Connection::commit)
.replaceOnFailure { _, _ -> /* handle error */ }
.replaceOnComplete(Connection::close)
Transactor.Strategy customStrategy =
Transactor.Strategy.empty()
.replaceOnBegin(conn -> conn.setAutoCommit(false))
.replaceOnSuccess(Connection::commit)
.replaceOnFailure((conn, throwable) -> { /* handle error */ })
.replaceOnComplete(Connection::close);
val customStrategy: Transactor.Strategy =
Strategy.empty()
.replaceOnBegin(conn => conn.setAutoCommit(false))
.replaceOnSuccess((conn: Connection) => conn.commit())
.replaceOnFailure((_, _) => { /* handle error */ })
.replaceOnComplete((conn: Connection) => conn.close())
Strategy Merging
Use mergeX methods to compose hooks — both the existing and new hook run in order. mergeListener composes listeners:
- Kotlin
- Java
- Scala
val base: Strategy = Transactor.defaultStrategy()
val withLogging: Strategy = base.mergeListener(logger)
Transactor.Strategy base = Transactor.defaultStrategy();
Transactor.Strategy withLogging = base.mergeListener(logger);
val base: Transactor.Strategy = Transactor.defaultStrategy()
val withLogging: Transactor.Strategy = base.mergeListener(logger)
The mergeListener convenience on Transactor creates a derived transactor with the listener merged into its strategy:
- Kotlin
- Java
- Scala
val txWithLogging: Transactor = tx.mergeListener(logger)
Transactor txWithLogging = tx.mergeListener(logger);
val txWithLogging: Transactor = tx.mergeListener(logger)