💾 データベース
📖 Exposedとは?
ExposedはKotlin用のSQLライブラリです。型安全なDSLでデータベース操作を簡単かつ安全に行うことができます!
💡 設定
build.gradle.kts
dependencies {
implementation("org.jetbrains.exposed:exposed-core:0.44.0")
implementation("org.jetbrains.exposed:exposed-dao:0.44.0")
implementation("org.jetbrains.exposed:exposed-jdbc:0.44.0")
// H2 데이터베이스 (개발용)
implementation("com.h2database:h2:2.2.224")
// PostgreSQL (프로덕션용)
// implementation("org.postgresql:postgresql:42.6.0")
}
🎯 基本的な使い方
テーブル定義
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
object Users : Table() {
val id = integer("id").autoIncrement()
val name = varchar("name", 50)
val email = varchar("email", 100)
override val primaryKey = PrimaryKey(id)
}
fun main() {
// 데이터베이스 연결
Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
driver = "org.h2.Driver"
)
transaction {
// 로깅 활성화
addLogger(StdOutSqlLogger)
// 테이블 생성
SchemaUtils.create(Users)
// 데이터 삽입
Users.insert {
it[name] = "홍길동"
it[email] = "hong@example.com"
}
// 조회
Users.selectAll().forEach {
println("${it[Users.name]}: ${it[Users.email]}")
}
}
}
🎨 CRUD操作
Create(作成)
transaction {
// 단건 삽입
Users.insert {
it[name] = "김철수"
it[email] = "kim@example.com"
}
// ID 받기
val userId = Users.insert {
it[name] = "이영희"
it[email] = "lee@example.com"
} get Users.id
println("생성된 ID: $userId")
}