はじめに
jOOQはMyBatisなどと同じORマッパーの一つで型安全にSQLを組み立てることができます。
この記事では、SpringBootのアプリケーションにjOOQを導入し、利用するところまでをまとめてみました。
環境
Library | Version |
---|---|
Java | openjkd-23 |
Kotlin | 1.9.25 |
SpringBoot | 3.5.4 |
実装
build.gradle.kts
spring-boot-starter-jooqを依存関係に追加します。
データベースはpostgreSQLを利用しました。
gradle build.gradle.kts
plugins {
kotlin("jvm") version "1.9.25"
kotlin("plugin.spring") version "1.9.25"
id("org.springframework.boot") version "3.5.4"
id("io.spring.dependency-management") version "1.1.7"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
description = "Demo project for Spring Boot"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-jooq")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll("-Xjsr305=strict")
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Controller
サンプルのプログラムを実装します。
kotlin BookController.kt
package com.example.jooqsample.controller
import com.example.jooqsample.entity.Book
import com.example.jooqsample.service.BookService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class BookController(
private val bookService: BookService
) {
@GetMapping("/books")
fun getBooks(): List<Book> {
return bookService.getBooks()
}
}
Service
jOOQを利用するサービスクラスを実装します。
DSLContextを用いてSQLを組み立てます。
kotlin BookService.kt
package com.example.jooqsample.service
import com.example.jooqsample.entity.Book
import org.jooq.DSLContext
import org.jooq.impl.DSL
import org.springframework.stereotype.Service
@Service
class BookService(
private val dsl: DSLContext
) {
fun getBooks(): List<Book> {
return dsl.select(
DSL.field("isbn", String::class.java),
DSL.field("title", String::class.java),
DSL.field("author", String::class.java),
DSL.field("publisher", String::class.java),
DSL.field("price", Int::class.java)
)
.from("main.book")
.fetch()
.map {
Book(
isbn = it.value1(),
title = it.value2(),
author = it.value3(),
publisher = it.value4(),
price = it.value5()
)
}
}
}
無事にjOOQを利用することができました!
終わりに
jOOQをSpringBootに導入するところまでを記事にしました。jOOQにはコードの自動生成など便利な機能がまだたくさんありますので、別の記事で紹介できればと思います。