A Lightweight ORM Framework for Kotlin

Emily Techscribe Avatar

·

Are you looking for an ORM framework that is lightweight and easy to use? Look no further than Exposed, a powerful tool for database access in Kotlin. Exposed provides two ways to access databases: a typesafe SQL wrapping DSL and a lightweight Data Access Objects (DAO). In this article, we’ll explore the features and functionalities of Exposed, discuss the supported databases, examine the dependencies, and provide code examples to demonstrate its usage.

Features and Functionalities

Exposed offers a wide range of features and functionalities that make it an excellent choice for database access in Kotlin. Here are some of its key features:

Typesafe SQL Wrapping DSL

The typesafe SQL wrapping DSL provided by Exposed allows you to perform database operations using a fluent and expressive API. With Exposed, you can write SQL queries in a type-safe manner, eliminating the risk of runtime errors commonly associated with string-based queries. This DSL makes it easier to write, read, and maintain your database code.

Lightweight Data Access Objects

Exposed also provides a lightweight implementation of Data Access Objects (DAOs). DAOs allow you to interact with your database using simple and intuitive methods, abstracting away the complexities of SQL. With Exposed’s DAOs, you can perform basic CRUD (Create, Read, Update, Delete) operations with ease, making database interactions more productive and efficient.

Database Engine Agnostic

One of the standout features of Exposed is its ability to mimic various database engines. Whether you’re working with H2, MariaDB, MySQL, Oracle, PostgreSQL, SQL Server, or SQLite, Exposed allows you to build applications without being tied to any specific database engine. This flexibility enables you to switch between different databases with minimal or no code changes, providing scalability and adaptability.

Supported Databases

Exposed supports a wide range of databases, making it a versatile choice for your projects. Here are some of the databases that are supported by Exposed:

  • H2
  • MariaDB
  • MySQL
  • Oracle
  • PostgreSQL (using the pgjdbc-ng JDBC driver)
  • SQL Server
  • SQLite

With support for these popular databases, Exposed gives you the freedom to choose the database that best suits your needs without sacrificing the power and convenience of the framework.

Dependencies

To get started with Exposed, you need to add the necessary dependencies to your project. Exposed consists of several modules, each serving a specific purpose. Here are the main Exposed modules:

  • exposed-core: The base module containing both the DSL API and mapping capabilities.
  • exposed-crypt: Provides additional column types for storing encrypted data in the database.
  • exposed-dao: A lightweight Data Access Objects (DAO) API.
  • exposed-java-time: Date-time extensions based on Java 8 Time API.
  • exposed-jdbc: Transport level implementation based on Java JDBC API.
  • exposed-jodatime: Date-time extensions based on the JodaTime library.
  • exposed-json: JSON and JSONB data type extensions.
  • exposed-kotlin-datetime: Date-time extensions based on kotlinx-datetime.
  • exposed-money: Extensions to support MonetaryAmount from “javax.money:money-api”.
  • exposed-spring-boot-starter: A starter for Spring Boot that allows you to use Exposed as the ORM instead of Hibernate.

You can add these modules to your project’s dependencies using Maven or Gradle. Make sure to specify the version of Exposed that you want to use.

Code Examples

To provide a better understanding of how Exposed works, let’s explore two code examples: one using the SQL DSL and another using the DAO.

SQL DSL Example:

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

object Users : Table() {
val id: Column = varchar(“id”, 10)
val name: Column = varchar(“name”, length = 50)
val cityId: Column = (integer(“city_id”) references Cities.id).nullable()

override val primaryKey = PrimaryKey(id, name = "PK_User_ID") // name is optional here

}

object Cities : Table() {
val id: Column = integer(“id”).autoIncrement()
val name: Column = varchar(“name”, 50)

override val primaryKey = PrimaryKey(id, name = "PK_Cities_ID")

}

fun main() {
Database.connect(“jdbc:h2:mem:test”, driver = “org.h2.Driver”, user = “root”, password = “”)

transaction {
    addLogger(StdOutSqlLogger)

    SchemaUtils.create(Cities, Users)

    // Perform database operations here

    SchemaUtils.drop(Users, Cities)
}

}
“`

DAO Example:

“`kotlin
import org.jetbrains.exposed.dao.
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.

import org.jetbrains.exposed.sql.transactions.transaction

object Users : IntIdTable() {
val name = varchar(“name”, 50).index()
val city = reference(“city”, Cities)
val age = integer(“age”)
}

object Cities: IntIdTable() {
val name = varchar(“name”, 50)
}

class User(id: EntityID) : IntEntity(id) {
companion object : IntEntityClass(Users)

var name by Users.name
var city by City referencedOn Users.city
var age by Users.age

}

class City(id: EntityID) : IntEntity(id) {
companion object : IntEntityClass(Cities)

var name by Cities.name
val users by User referrersOn Users.city

}

fun main() {
Database.connect(“jdbc:h2:mem:test”, driver = “org.h2.Driver”, user = “root”, password = “”)

transaction {
    addLogger(StdOutSqlLogger)

    SchemaUtils.create(Cities, Users)

    // Perform database operations here

    SchemaUtils.drop(Users, Cities)
}

}
“`

The above examples demonstrate how to set up and perform basic database operations using Exposed’s SQL DSL and DAO. You can customize these examples to fit your specific requirements and build robust database-driven applications in Kotlin.

Conclusion

In this article, we introduced Exposed, a lightweight ORM framework for Kotlin. We explored the features and functionalities of Exposed, discussed the supported databases, examined the dependencies, and provided code examples for both the SQL DSL and DAO implementations. Whether you’re building a small project or a large-scale application, Exposed can simplify and streamline your database interactions in Kotlin.

To learn more about Exposed, check out the official documentation, join the Kotlinlang Slack Channel #exposed, and explore the project’s GitHub repository.

Remember, with Exposed, you can enjoy the benefits of a lightweight ORM framework while harnessing the power of Kotlin for seamless and efficient database access.

Happy coding with Exposed!

Leave a Reply

Your email address will not be published. Required fields are marked *