In Hibernate it's normal to start the transaction ...
# exposed
b
In Hibernate it's normal to start the transaction as far "out" as possible, for example on the endpoint function itself or in the service layer. Is this recommended with Exposed as well, or do you only wrap as little as possible in a transaction?
s
Seems entirely dependent on your use case. I dont think Exposed is opinionated either way.
f
In Exposed it is generally recommended to wrap as little as possible in a transaction rather than starting it "far out" (e.g., at the endpoint or service layer) as is common with Hibernate. This is because Exposed relies on thread-local variables for transactions, which can be disrupted if using coroutines or switching dispatchers, which may not resume in the same thread. While Exposed provides coroutine-friendly options like
newSuspendedTransaction()
and
Transaction.withSuspendTransaction()
to address these issues, keeping transactions small and localized minimizes thread-related risks. If you are using Ktor, then there is a plugin on the works that would allow transactions to start at endpoint level managing all the thread switching automatically, but seems is still under review (https://youtrack.jetbrains.com/issue/KTOR-5310/Transaction-plugin-for-Databases-start-with-Exposed)
d
From a database best practices, transactions should be atomic operations.