DB access using Exposed

I used Exposed for DB access in kotlin, so it's a memorandum. To check the operation, I set up a test DB with Docker and checked it.

I referred to the following for the environment construction of DOcker. ・ Introduction of WSL2 and Docker https://qiita.com/KoKeCross/items/a6365af2594a102a817b

・ WSL2 memory depletion measures https://qiita.com/yoichiwo7/items/e3e13b6fe2f32c4c6120

What is Exposed?

A SQL library written in Kotlin. https://github.com/JetBrains/Exposed

Sample program

First, the docker-compose.yaml file for creating a DB with Docker.

version: '3'
services:
  db:
    image: postgres:12.3
    ports:
      - 5433:5432
    environment:
      POSTGRES_USER: admin
      POSTGRES_PASSWORD: admin
      POSTGRES_DB: test_db

Next is the table definition.

object Member : Table("member") {
    val id = integer("member_id").autoIncrement().primaryKey()
    val name = varchar("name", 50)
    val age = integer("age")
}

Finally the main function.

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

fun main() {
    Database.connect("jdbc:postgresql://localhot:5433/test_db", "org.postgresql.Driver", "admin", "admin")

    transaction {
        addLogger(StdOutSqlLogger)

        create(Member)

        Member.insert {
            it[id] = 1
            it[name] = "abc"
            it[age] = 20
        }

        Member.insert {
            it[id] = 2
            it[name] = "efd"
            it[age] = 30
        }

        for(member in Member.selectAll()) {
            println("${member[Member.id]}: ${member[Member.name]}: ${member[Member.age]}")
        }

        Member.update({Member.name eq "abc"}) {
            it[name] = "AIUEO"
        }

        for(member in Member.selectAll()) {
            println("${member[Member.id]}: ${member[Member.name]}: ${member[Member.age]}")
        }

        Member.deleteAll()

        drop(Member)
    }
}

It's a defeat, but for the time being, I was able to confirm that CRUD can be done.

Recommended Posts

DB access using Exposed
DB access using repository with SpringData.
DB programming using EclipseLink part1
[Rails] Reflection to db using seeds.rb
Insert data into DB using Yaml file
ERRORCODE = -4471 occurs in Java application using Db2.
Generate DB documentation using SchemaSpy in Gradle
[Java] Let's make a DB access library!