Created
August 17, 2021 08:25
-
-
Save nakamura-to/18e65bdb42ccef44886ff7c014911624 to your computer and use it in GitHub Desktop.
KomapperでWhere宣言を合成する例
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.KomapperAutoIncrement | |
import org.komapper.annotation.KomapperEntity | |
import org.komapper.annotation.KomapperId | |
import org.komapper.core.dsl.EntityDsl | |
import org.komapper.core.dsl.SchemaDsl | |
import org.komapper.core.dsl.expression.ColumnExpression | |
import org.komapper.core.dsl.scope.WhereDeclaration | |
import org.komapper.jdbc.JdbcDatabase | |
import org.komapper.tx.jdbc.withTransaction | |
// 年齢を表すクラス | |
@JvmInline | |
value class Age(val value: Int) | |
// 人を表すエンティティクラス | |
@KomapperEntity | |
data class Person( | |
@KomapperId @KomapperAutoIncrement | |
val id: Int = 0, | |
val name: String, | |
val age: Age | |
) { | |
companion object | |
} | |
// 成年の検索条件 | |
fun ColumnExpression<Age, Int>.adult(): WhereDeclaration = { | |
this@adult greaterEq Age(20) | |
} | |
// 生産年齢の検索条件 | |
fun ColumnExpression<Age, Int>.workingAge(): WhereDeclaration = { | |
this@workingAge less Age(65) | |
and(adult()) // 成年の検索条件を再利用 | |
} | |
fun main() { | |
val db = JdbcDatabase.create("jdbc:h2:mem:quickstart;DB_CLOSE_DELAY=-1") | |
db.withTransaction { | |
val p = Person.meta | |
// スキーマ作成 | |
db.runQuery { SchemaDsl.create(p) } | |
// データを3件追加 | |
db.runQuery { | |
EntityDsl.insert(p).multiple( | |
Person(name = "aaa", age = Age(10)), | |
Person(name = "bbb", age = Age(30)), | |
Person(name = "ccc", age = Age(70)), | |
) | |
} | |
println("成年の定義で検索") | |
db.runQuery { EntityDsl.from(p).where(p.age.adult()) }.forEach { | |
println(it) | |
} | |
println("生産年齢の定義で検索") | |
db.runQuery { EntityDsl.from(p).where(p.age.workingAge()) }.forEach { | |
println(it) | |
} | |
} | |
} |
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
17:22:41.477 [main] DEBUG org.komapper.SQL - insert into person (name, age) values (?, ?), (?, ?), (?, ?) | |
成年の定義で検索 | |
17:22:41.513 [main] DEBUG org.komapper.SQL - select t0_.id, t0_.name, t0_.age from person as t0_ where t0_.age >= ? | |
Person(id=2, name=bbb, age=Age(value=30)) | |
Person(id=3, name=ccc, age=Age(value=70)) | |
生産年齢の定義で検索 | |
17:22:41.567 [main] DEBUG org.komapper.SQL - select t0_.id, t0_.name, t0_.age from person as t0_ where t0_.age < ? and (t0_.age >= ?) | |
Person(id=2, name=bbb, age=Age(value=30)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment