I'm excited to announce the release of Kapper 1.2, which introduces a small but meaningful enhancement.
In line with Kapper's philosophy of being lightweight and non-intrusive, we've added withTransaction
as an extension method to both Connection
and DataSource
. This addition doesn't abstract away or replace the underlying functionality—it's purely syntactic sugar designed to save you from writing repetitive boilerplate code.
Before: Transactions in Kapper 1.0
Here's an example of how you might execute a couple of queries within a transaction using Kapper 1.0:
dataSource.connection.use {
try {
it.autoCommit = false
it.execute(
"""
INSERT INTO villains(id, name)
VALUES (:id, :name)
""".trimIndent(),
"id" to villain.id,
"name" to villain.name,
)
it.execute(
"""
INSERT INTO battles(super_hero_id, villain_id, battle_date, updated_ts)
VALUES (:super_hero_id, :villain_id, :date, NOW())
""".trimIndent(),
"super_hero_id" to superHero.id,
"villain_id" to villain.id,
"date" to date,
)
it.commit()
} catch (ex: SQLException) {
try {
it.rollback()
} catch (rollbackException: Exception) {
ex.addSuppressed(rollbackException)
}
throw ex
}
}
While this code is clear, it involves a fair amount of boilerplate for managing exceptions and transactions.
After: Transactions in Kapper 1.2
With Kapper 1.2, the same logic can now be written more concisely:
dataSource.withTransaction {
it.execute(
"""
INSERT INTO villains(id, name)
VALUES (:id, :name)
""".trimIndent(),
"id" to villain.id,
"name" to villain.name,
)
it.execute(
"""
INSERT INTO battles(super_hero_id, villain_id, battle_date, updated_ts)
VALUES (:super_hero_id, :villain_id, :date, NOW())
""".trimIndent(),
"super_hero_id" to superHero.id,
"villain_id" to villain.id,
"date" to date,
)
}
How withTransaction Simplifies Your Code
The withTransaction function automatically:
- Creates a connection.
- Starts and commits the transaction.
- Rolls back the transaction if an exception occurs.
- Ensures the connection is properly closed.
This results in cleaner, more readable code while retaining the flexibility to use the native JDBC API whenever needed.
Kapper 1.2 is now available on Maven Central. For more details, check out the GitHub repository or explore the examples.
I’d love to hear your feedback—let me know what you think!
Top comments (0)