Created
July 21, 2024 07:41
-
-
Save nakamura-to/53b0fb3084bcf6af48d9cb8046e4b327 to your computer and use it in GitHub Desktop.
Komapperにおける複数クエリ共通の検索条件の定義方法 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.core.dsl.metamodel.EntityMetamodel | |
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 { | |
QueryDsl.from(e).where { | |
// "e.createdAt greater dateTime" と記述するのと同じ意味 | |
commonWhere(e, dateTime)() | |
} | |
} | |
println(employees) | |
// Addressの検索 | |
val addresses = database.runQuery { | |
QueryDsl.from(a).where { | |
// "a.createdAt greater dateTime" と記述するのと同じ意味 | |
commonWhere(a, dateTime)() | |
} | |
} | |
println(addresses) | |
} | |
} | |
// 複数のクエリで利用できる検索条件 | |
fun commonWhere(metamodel: EntityMetamodel<*, *, *>, dateTime: LocalDateTime) : WhereDeclaration { | |
val createdAt = metamodel.properties().firstOrNull { it.name == "createdAt" } as? PropertyExpression<LocalDateTime, LocalDateTime> | |
return { | |
if (createdAt != null) { | |
createdAt greater dateTime | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment