Študijné materiály

V reálnych projektoch budeme pravdepodobne potrebovať napojiť server na databázu. Ukážeme si použitie H2 - ľahkej embedded databázy:

18.4.1 Nastavenie

V build.gradle.kts pridáme H2 a Exposed (DSL pre prácu s DB):

dependencies {
    // ... predchadzajuce dependencies
    implementation("org.jetbrains.exposed:exposed-core:0.56.0")
    implementation("org.jetbrains.exposed:exposed-jdbc:0.56.0")
    implementation("com.h2database:h2:2.3.232")
}

18.4.2 Definícia tabuľky

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

object Users : Table() {
    val id = integer("id").autoIncrement()
    val name = varchar("name", length = 100)
    val email = varchar("email", length = 100)

    override val primaryKey = PrimaryKey(id)
}

fun initDB() {
    Database.connect("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver")
    transaction {
        SchemaUtils.create(Users)
    }
}

18.4.3 CRUD operácie

fun getAllUsers(): List<Pair<Int, String>> = transaction {
    Users.selectAll().map { it[Users.id] to it[Users.name] }
}

fun addUser(name: String, email: String): Int = transaction {
    Users.insertAndGetId {
        it[Users.name] = name
        it[Users.email] = email
    }.value
}

fun deleteUser(id: Int): Boolean = transaction {
    Users.deleteWhere { Users.id eq id } > 0
}

18.4.4 Integrácia s Ktor serverom

fun main() {
    initDB()

    embeddedServer(Netty, port = 8080) {
        routing {
            get("/users") {
                val users = getAllUsers()
                call.respond(users)
            }
            post("/users") {
                val (name, email) = call.receive<Map<String, String>>()
                val id = addUser(name, email)
                call.respond(mapOf("id" to id))
            }
        }
    }.start(wait = true)
}

H2 databáza je len na ukážku. V reálnom projekte by sme použili PostgreSQL alebo MySQL.

Úlohy

Úloha 1

Pridaj H2 a Exposed závislosti a vytvor tabuľku Produkty s názvom a cenou.

Úloha 2

Implementuj funkcie na vloženie a načítanie všetkých produktov v transakcii.

Úloha 3

Napoj tieto funkcie na GET a POST endpoint Ktor servera.