Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Last active July 21, 2024 06:55
Show Gist options
  • Save nakamura-to/8dc3a46f2ba42678d1bb367f6fb57033 to your computer and use it in GitHub Desktop.
Save nakamura-to/8dc3a46f2ba42678d1bb367f6fb57033 to your computer and use it in GitHub Desktop.
Komapperにおける複数クエリ共通の検索条件の定義方法
package org.komapper.quickstart
import org.komapper.annotation.*
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.expression.PropertyExpression
import org.komapper.core.dsl.expression.WhereDeclaration
import org.komapper.jdbc.JdbcDatabase
import java.time.LocalDateTime
@KomapperEntity
data class Employee(
@KomapperId @KomapperAutoIncrement
val id: Int = 0,
val name: String,
@KomapperVersion
val version: Int = 0,
@KomapperCreatedAt
val createdAt: LocalDateTime = LocalDateTime.MIN,
@KomapperUpdatedAt
val updatedAt: LocalDateTime = LocalDateTime.MIN,
)
@KomapperEntity
data class Address(
@KomapperId @KomapperAutoIncrement
val id: Int = 0,
val name: String,
@KomapperVersion
val version: Int = 0,
@KomapperCreatedAt
val createdAt: LocalDateTime = LocalDateTime.MIN,
@KomapperUpdatedAt
val updatedAt: LocalDateTime = LocalDateTime.MIN,
)
fun main() {
val database = JdbcDatabase("jdbc:h2:mem:quickstart;DB_CLOSE_DELAY=-1")
database.withTransaction {
val e = Meta.employee
val a = Meta.address
// EmployeeとAddressのスキーマ作成
database.runQuery {
QueryDsl.create(e, a)
}
// Employeeの登録
database.runQuery {
QueryDsl.insert(e).single(Employee(name = "Alice"))
}
// Addressの登録
database.runQuery {
QueryDsl.insert(a).single(Address(name = "Tokyo"))
}
val dateTime = LocalDateTime.of(2024, 1, 1, 0, 0, 0)
// Employeeの検索
val employees = database.runQuery {
// select t0_.id, t0_.name, t0_.version, t0_.created_at, t0_.updated_at from employee as t0_ where t0_.created_at > ?
QueryDsl.from(e).where {
// "e.createdAt greater dateTime" と記述するのと同じ意味
commonWhere(e.createdAt, dateTime)()
}
}
println(employees)
// Addressの検索
val addresses = database.runQuery {
// select t0_.id, t0_.name, t0_.version, t0_.created_at, t0_.updated_at from address as t0_ where t0_.created_at > ?
QueryDsl.from(a).where {
// "a.createdAt greater dateTime" と記述するのと同じ意味
commonWhere(a.createdAt, dateTime)()
}
}
println(addresses)
}
}
// 複数のクエリで利用できる検索条件
fun commonWhere(createdAt: PropertyExpression<LocalDateTime, LocalDateTime>, dateTime: LocalDateTime) : WhereDeclaration {
return {
createdAt greater dateTime
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment