Search code examples
javaintellij-ideakotlinkotlin-exposed

How to use Kotlin with H2 and SQLite in Intellij


When I try to use Kotlin in Intellij with either SQLite or H2, Intellij gives me this error:

Exception in thread "main" java.lang.ClassNotFoundException: org.h2.Driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.jetbrains.exposed.sql.Database$Companion.connect(Database.kt:91)
    at org.jetbrains.exposed.sql.Database$Companion.connect$default(Database.kt:90)
    at MainKt.main(main.kt:9)

This is my Gradle file:

buildscript {
    ext.kotlin_version = '1.2.20'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.h2.Driver"
    }
}

group '1'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin'

repositories {
    mavenCentral()
    maven {
        url  "https://dl.bintray.com/kotlin/exposed"
    }
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile 'org.jetbrains.exposed:exposed:0.9.1'

}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

This is my Kotlin file, where I try to use Exposed to interface with H2e some data persistence with Kotlin:

import org.jetbrains.exposed.sql.StdOutSqlLogger
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.selectAll

fun main(args: Array<String>) {
    Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

    transaction {
        logger.addLogger(StdOutSqlLogger)

        val stPeteId = Cities.insert {
            it[name] = "St. Petersburg"
        } get Cities.id

        println("Cities: ${Cities.selectAll()}")
    }
}

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

data class City(val id: Int, val name: String)

How do I use Kotlin with a database? This is not for Android; just a personal project in Intellij that I want to use eventually on a PC.


Solution

  • You actually need the h2 driver, wether you're in java or kotlin. Add the com.h2database:h2 dependency to your gradle file and add the maven central if needed.

    By the way, there's nothing wrong with your kotlin code. This would also not work if called from java like this, since you're missing the dependencies.