Version v1.6 of the documentation is no longer actively maintained. The site that you are currently viewing is an archived snapshot. For up-to-date documentation, see the latest version.

Quickstart

Try Komapper with minimum settings

Overview

We show you how to create an application that uses JDBC to access H2 Database Engine.

Prerequisites

  • JDK 11 or later
  • Gradle 6.7.1 or later

Install

Install JDK and Gradle.

Create Application

Build Script

Write your build scripts using Gradle Kotlin DSL.

Include the following code in your build.gradle.kts:

plugins {
    application
    id("com.google.devtools.ksp") version "1.8.0-1.0.8"
    kotlin("jvm") version "1.8.0"
}

application {
    mainClass.set("org.komapper.quickstart.ApplicationKt")
}

dependencies {
    val komapperVersion = "1.6.0"
    platform("org.komapper:komapper-platform:$komapperVersion").let {
        implementation(it)
        ksp(it)
    }
    implementation("org.komapper:komapper-starter-jdbc")
    implementation("org.komapper:komapper-dialect-h2-jdbc")
    ksp("org.komapper:komapper-processor")
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.2")
}

kotlin {
    sourceSets.main {
        kotlin.srcDir("build/generated/ksp/main/kotlin")
    }
}

repositories {
    mavenCentral()
}

tasks {
    withType<Test>().configureEach {
        useJUnitPlatform()
    }
}

There are three key points in this build script:

  1. Specify the com.google.devtools.ksp plugin in the plugins block
  2. Use Komapper modules with the same version number in the dependencies block.
  3. Specify the directory of the output source code in the kotlin block.

com.google.devtools.ksp is a plugin for Kotlin Symbol Processing API. It is required for code generation at compile time. The value before the hyphen in the plugin version number must be equal to or greater than the version of Kotlin you are using.

The following is an overview of each of the Komapper modules specified in the dependencies block:

  • komapper-platform: Provides recommended versions of Komapper modules.
  • komapper-starter-jdbc: This module contains a set of modules that are necessary and useful for JDBC access using Komapper.
  • komapper-dialect-h2-jdbc: This module is necessary to connect to the H2 Database Engine.
  • komapper-processor: A module to generate code at compile-time. Note that they are declared using the keyword ksp. The ksp keyword is provided by the Kotlin Symbol Processing API plugin.

In the kotlin block, we tell Gradle that the generated code should be treated as source code.

Source code

First, create an entity class:

@KomapperEntity
data class Employee(
  @KomapperId @KomapperAutoIncrement
  val id: Int = 0,
  val name: String,
  @KomapperVersion
  val version: Int = 0,
  @KomapperCreatedAt
  val createdAt: LocalDateTime = LocalDateTime.MIN,
  @KomapperUpdatedAt
  val updatedAt: LocalDateTime = LocalDateTime.MIN,
)

Once you have finished creating the above class, build it. The metamodel code will be output and can be used in subsequent code.

Next, create a main logic:

fun main() {
  // (1) create a database instance
  val database = JdbcDatabase("jdbc:h2:mem:quickstart;DB_CLOSE_DELAY=-1")

  // (2) start transaction
  database.withTransaction {

    // (3) get an entity metamodel
    val e = Meta.employee

    // (4) create schema
    database.runQuery {
      QueryDsl.create(e)
    }

    // (5) insert multiple employees at once
    database.runQuery {
      QueryDsl.insert(e).multiple(Employee(name = "AAA"), Employee(name = "BBB"))
    }

    // (6) select all
    val employees = database.runQuery {
      QueryDsl.from(e).orderBy(e.id)
    }

    // (7) print all results
    for ((i, employee) in employees.withIndex()) {
      println("RESULT $i: $employee")
    }
  }
}
  1. Create an instance representing the database by providing a connection string. This instance is needed for transaction control and query execution.
  2. Start the transaction. You can also specify transaction attributes and isolation levels at the start.
  3. Get an instance of the metamodel class generated by the source code. Instances of the metamodel are exposed as extended properties of the Meta object.
  4. Generate a schema using the metamodel. This feature is useful for creating simple samples, but is deprecated for use in production-level applications.
  5. Add multiple entities at once.
  6. Retrieve all records as entities.
  7. Output the retrieved entities.

Build

To build your application, execute the following Gradle command:

$ gradle build

After executing the command, check the build/generated/ksp/main/kotlin directory. You can see that the code generated by Kotlin Symbol Processing API exists.

Run

To run your application, execute the following Gradle command:

$ gradle run

When you run the application, you will see the following output on the console:

21:00:53.099 [main] DEBUG org.komapper.SQL - create table if not exists employee (id integer not null auto_increment, name varchar(500) not null, version integer not null, created_at timestamp not null, updated_at timestamp not null, constraint pk_employee primary key(id));
21:00:53.117 [main] DEBUG org.komapper.SQL - insert into employee (name, version, created_at, updated_at) values (?, ?, ?, ?), (?, ?, ?, ?)
21:00:53.140 [main] DEBUG org.komapper.SQL - select t0_.id, t0_.name, t0_.version, t0_.created_at, t0_.updated_at from employee as t0_ order by t0_.id asc
RESULT 0: Employee(id=1, name=AAA, version=0, createdAt=2021-05-05T21:00:53.115127, updatedAt=2021-05-05T21:00:53.115127)
RESULT 1: Employee(id=2, name=BBB, version=0, createdAt=2021-05-05T21:00:53.115250, updatedAt=2021-05-05T21:00:53.115250)

You can see that the Employee instance has been set with ID and timestamp. These were set automatically by Komapper.

Get complete code

To get complete code, see https://github.com/komapper/komapper-quickstart

In the above repository, Gradle Wrapper is available. So you can execute ./gradlew build and ./gradlew run instead of gradle build and gradle run.

Last modified January 7, 2023: Add v1.6 (380cbba)