Kotlin Exposed

Kotlin Exposed

Overview

Exposed is a lightweight SQL library for Kotlin developed by JetBrains.

Features

  • Provides a type-safe DSL (Domain Specific Language).
  • Lets you write queries in an ORM (Object-Relational Mapping) style.
  • Supports JDBC and R2DBC drivers.
  • Provides features such as transaction management and migrations.
  • Officially supports H2, MySQL, MariaDB, Oracle, PostgreSQL, SQL Server, and SQLite databases.
  • Uses Kotlin types, so type errors can be caught at compile time.
  • Provides both DSL and DAO APIs, so you can choose the approach that best fits your use case.
  • Coroutine compatibility: supports asynchronous programming so blocking work can be handled efficiently.
    • Exposed communicates with databases internally through JDBC, and JDBC is a traditional blocking API. Therefore, when a database operation is performed, the thread is blocked until the operation finishes. Exposed itself does not provide a non-blocking API, but when it is used with coroutines, coroutine dispatchers can run blocking work on an appropriate thread pool. This makes it possible to perform database work without blocking the main thread.

Database Access Approaches

Exposed provides two levels of database access.

  • A DSL (Domain Specific Language) approach that maps SQL
    • You can write queries in a SQL-like form, using familiar SQL concepts while benefiting from Kotlin’s type safety.
  • A lightweight DAO (Data Access Object) approach
    • It provides an object-oriented approach similar to Hibernate, a traditional ORM framework.
    • It handles database entities through objects and represents tables as classes, so database records can be mapped directly to objects.
// DSL approach
val users = UsersTable.select { UsersTable.age greater 20 }

// DAO approach
val user = User.findById(1)

You can choose the approach that best fits your project’s requirements.