Improve Coroutines transaction API
As a follow-up of gh-22915, the purpose of this commit is to improve Coroutines programmatic transaction API to make it more consistent with the Java one and more idiomatic. For suspending functions, this commit changes the TransactionalOperator.transactional extension with a suspending lambda parameter to a TransactionalOperator.executeAndAwait one which is conceptually closer to TransactionalOperator.execute Java API so more consistent. For Flow, the TransactionalOperator.transactional extension is correct but would be more idiomatic as a Flow extension. This commit also adds code samples to the reference documentation. Closes gh-23627
This commit is contained in:
@@ -577,8 +577,51 @@ class UserHandler(builder: WebClient.Builder) {
|
||||
=== Transactions
|
||||
|
||||
Transactions on Coroutines are supported via the programmatic variant of the Reactive
|
||||
transaction management provided as of Spring Framework 5.2. `TransactionalOperator.transactional`
|
||||
extensions with suspending lambda and Kotlin `Flow` parameter are provided for that purpose.
|
||||
transaction management provided as of Spring Framework 5.2.
|
||||
|
||||
For suspending functions, a `TransactionalOperator.executeAndAwait` extension is provided.
|
||||
|
||||
[source,kotlin,indent=0]
|
||||
----
|
||||
import org.springframework.transaction.reactive.executeAndAwait
|
||||
|
||||
class PersonRepository(private val operator: TransactionalOperator) {
|
||||
|
||||
suspend fun initDatabase() = operator.executeAndAwait {
|
||||
insertPerson1()
|
||||
insertPerson2()
|
||||
}
|
||||
|
||||
private suspend fun insertPerson1() {
|
||||
// INSERT SQL statement
|
||||
}
|
||||
|
||||
private suspend fun insertPerson2() {
|
||||
// INSERT SQL statement
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
For Kotlin `Flow`, a `Flow<T>.transactional` extension is provided.
|
||||
|
||||
[source,kotlin,indent=0]
|
||||
----
|
||||
import org.springframework.transaction.reactive.transactional
|
||||
|
||||
class PersonRepository(private val operator: TransactionalOperator) {
|
||||
|
||||
fun updatePeople() = findPeople().map(::updatePerson).transactional(operator)
|
||||
|
||||
private fun findPeople(): Flow<Person> {
|
||||
// SELECT SQL statement
|
||||
}
|
||||
|
||||
private suspend fun updatePerson(person: Person): Person {
|
||||
// UPDATE SQL statement
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
[[kotlin-spring-projects-in-kotlin]]
|
||||
== Spring Projects in Kotlin
|
||||
|
||||
Reference in New Issue
Block a user