Database Interaction with Exposed

Database Interaction with Exposed

Exposed is a lightweight SQL library for Kotlin that provides a typesafe way to interact with databases. It abstracts the underlying SQL syntax and allows developers to work with database records as Kotlin objects. This topic will cover how to set up Exposed, perform CRUD operations, and handle transactions effectively.

Setting Up Exposed

To use Exposed in your Kotlin project, you need to add the necessary dependencies in your build.gradle.kts file:

`kotlin dependencies { implementation("org.jetbrains.kotlinx:exposed-core:0.36.2") implementation("org.jetbrains.kotlinx:exposed-dao:0.36.2") implementation("org.jetbrains.kotlinx:exposed-jdbc:0.36.2") implementation("org.xerial.sqlite-jdbc:3.36.0.3") // Example for SQLite } `

After adding the dependencies, you can initialize the database connection:

`kotlin import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction

fun initDatabase() { Database.connect("jdbc:sqlite:sample.db", driver = "org.sqlite.JDBC") transaction { SchemaUtils.create(Users) } } `

Defining Tables

In Exposed, tables are represented as Kotlin objects. Let's define a simple Users table:

`kotlin object Users : Table() { val id = integer("id").autoIncrement() val name = varchar("name", 50) val age = integer("age") override val primaryKey = PrimaryKey(id) } `

Performing CRUD Operations

Create

To insert a new user into the database:

`kotlin fun addUser(name: String, age: Int) { transaction { Users.insert { it[Users.name] = name it[Users.age] = age } } } `

Read

To read all users from the database:

`kotlin fun getAllUsers(): List> { return transaction { Users.selectAll().map { it[Users.id] to it[Users.name] } } } `

Update

To update a user's information:

`kotlin fun updateUser(userId: Int, newName: String) { transaction { Users.update({ Users.id eq userId }) { it[name] = newName } } } `

Delete

To delete a user from the database:

`kotlin fun deleteUser(userId: Int) { transaction { Users.deleteWhere { Users.id eq userId } } } `

Handling Transactions

Exposed makes it easy to manage transactions. You can group multiple operations in a single transaction:

`kotlin fun addMultipleUsers(users: List>) { transaction { users.forEach { (name, age) -> addUser(name, age) } } } `

Conclusion

Exposed provides a powerful and expressive way to handle database interactions in Kotlin applications. By leveraging its typesafe DSL, you can efficiently perform CRUD operations and manage transactions, ultimately leading to cleaner and more maintainable code.

---

Back to Course View Full Topic