Transaction
- Kotlin course
- Advanced
- Lesson 33/83
- 5 min
Learn SQL operations with the transaction block.
What is a transaction?
A transaction in Exposed is the block where all database operations run. A transaction { ... } call opens the block; the transaction commits when it ends.
Example: transaction { Users.insert { it[name] = "Ayşe" } }. At the end of this block the insert is committed automatically. If an exception throws inside the block, the transaction rolls back. This keeps the database consistent. Exposed ensures all queries inside a transaction use the same connection. No query can run outside a transaction.
Using transactions
All database work happens inside a transaction { ... } block. Exposed commits the transaction automatically when the block ends.
Example: transaction { val user = Users.select { Users.id eq 1 }.first(); println(user[Users.name]) }. This block reads a record and prints its name. If multiple operations run in one transaction they are atomic; either all succeed or none. This matters for scenarios that need consistency, like a money transfer. transaction is not a suspending function; it runs synchronously.
Practice Open a transaction block
Open a connection with Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver"). Inside a transaction { ... } block, print println("Transaction ready").
Starter code
// Transaction
// write here
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
fun main() {
}Sample solution
fun main() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
println("Transaction ready")
}
}Expected output
Transaction ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match transaction parts
| Term | Meaning |
|---|---|
transaction |
Transaction block |
commit |
Write |
rollback |
Rollback |
insert |
Add record |
2 What happens when a transaction block ends?
- It commits automatically Correct answer
- The transaction rolls back
- The connection closes
- A new transaction opens
Explanation: The transaction commits automatically when the block ends.
3 Complete the transaction block
____ {
Users.insert { it[Users.name] = "Ayşe" }
}
transaction {
Users.insert { it[Users.name] = "Ayşe" }
}
Explanation: transaction opens a database operation.