CodeBlanks Logo Icon CodeBlanks

Exposed

Learn the JetBrains Exposed ORM.

What is Exposed?

Exposed is JetBrains' SQL ORM library for Kotlin. It declares tables as Kotlin objects and lets you write SQL queries in a type safe way.

You open a connection with Database.connect(url, driver). All work happens inside a transaction { ... } block. Tables are declared with object Users : Table() { ... }. Exposed offers a Kotlin API instead of raw SQL; this gives compile time checks and code completion. In this lesson you will set up the basic connection.

Database connection

To connect to a database with Exposed you call Database.connect(url, driver). The URL and driver are database specific.

Example: Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver"). H2 in memory is a common choice for testing. PostgreSQL or MySQL use their own driver and URL. The connection is shared by all transaction blocks. Real apps use a connection pool like HikariCP for performance.

Practice Database connection and transaction

Open a connection with Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver"). Inside a transaction { ... } block, print println("Exposed ready").

Starter code

Main.kt
// Exposed
// write here
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction

fun main() {
    
}

Sample solution

Main.kt
fun main() {
    Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
    transaction {
        println("Exposed ready")
    }
}

Expected output

Exposed ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is Exposed used for?

  • Making HTTP requests
  • Serializing JSON
  • SQL database operations Correct answer
  • Drawing UI

Explanation: Exposed is a Kotlin ORM for SQL database operations.

2 Complete the connect call

Question
Database.____("jdbc:h2:mem:test", driver = "org.h2.Driver")
Answer
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

Explanation: Database.connect opens the connection.

3 Match Exposed parts

Term Meaning
Database.connect Connection
transaction Transaction block
Table Table base
object Singleton declaration

All lessons in Advanced