Sling Academy
Home/Kotlin/Using Database Libraries like Exposed for Kotlin

Using Database Libraries like Exposed for Kotlin

Last updated: December 01, 2024

Introduction

Kotlin is a versatile and expressive programming language that seamlessly integrates with existing Java libraries. When it comes to database operations, utilizing libraries specifically designed for Kotlin, like Exposed, can simplify and streamline the database interaction process.

Setting Up Exposed in Your Project

First, you need to add the Exposed library to your Kotlin project. You can use Gradle for this purpose. Add the following dependency to your build.gradle.kts file:


// build.gradle.kts
implementation("org.jetbrains.exposed:exposed-core:")
implementation("org.jetbrains.exposed:exposed-dao:")
implementation("org.jetbrains.exposed:exposed-jdbc:")

Don’t forget to specify the Exposed version that you wish to use. Additionally, ensure you have the appropriate JDBC driver for your database.

Connecting to a Database

Once the library is added, you can connect to the database using Exposed. Here’s how to connect to a SQLite database for simplicity:


// Repository.kt
import org.jetbrains.exposed.sql.Database

Database.connect("jdbc:sqlite:data.db", driver = "org.sqlite.JDBC")

Defining Database Tables

Exposed lets you conveniently define database schemas through Kotlin code. For instance, to define a simple Users table, you would write:


// Users.kt
import org.jetbrains.exposed.sql.Table

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

In this setup, the Users table has three columns: id, name, and age.

Performing CRUD Operations

With the table defined, you can perform CRUD (Create, Read, Update, Delete) operations using Exposed:

Inserting Data


// Insert Data
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.insert

transaction {
    Users.insert {
        it[name] = "John Doe"
        it[age] = 30
    }
}

Reading Data


// Read Data
import org.jetbrains.exposed.sql.selectAll

transaction {
    val users = Users.selectAll()
    for (user in users) {
        println("User ID: ", user[Users.id])
        println("Name: ", user[Users.name])
        println("Age: ", user[Users.age])
    }
}

Updating Data


// Update Data
import org.jetbrains.exposed.sql.update

transaction {
    Users.update({ Users.id eq 1 }) {
        it[name] = "Jane Doe"
        it[age] = 25
    }
}

Deleting Data


// Delete Data
import org.jetbrains.exposed.sql.deleteWhere

transaction {
    Users.deleteWhere { Users.id eq 1 }
}

Conclusion

Kotlin's Exposed library offers a powerful way to manage database operations with clean, type-safe, and expressive syntax. It abstracts many of the common database tasks, making database interactions more manageable and intuitive. If you're working with Kotlin and databases, Exposed is certainly worth exploring for your next project.

Next Article: Building a Multi-Database Application with Kotlin

Previous Article: Best Practices for NoSQL Databases in Kotlin Applications

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin