728x90
CASE๋ฌธ
select, ์กฐ๊ฑด์ (where), orderBy ์์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
๋จ์ํ ์กฐ๊ฑด
/**
* (DB๊ฐ ์๋๋ผ ์ ํ๋ฆฌ์ผ์ด์
์์ ํ๋๊ฒ์ ์ถ์ฒ)
* Case ๋ฌธ
*/
@Test
fun testCase() {
//given
val fetch = query
.select(
member.age
.`when`(10).then("์ด์ด")
.`when`(20).then("์ค๋ฌด์ด")
.otherwise("๊ธฐํ")
)
.from(member)
.fetch()
fetch.forEach { println(it) }
}
๋ณต์กํ ์กฐ๊ฑด - CaseBuilder ์ฌ์ฉ
/**
* ๋ณต์กํ Case ๋ฌธ
* CaseBuilder ์ฌ์ฉ
*/
@Test
fun complexCase() {
//given
val fetch = query
.select(
CaseBuilder()
.`when`(member.age.between(0, 20)).then("0~20์ด")
.`when`(member.username.contains("member")).then("member ํฌํจ")
.otherwise("zz")
)
.from(member)
.fetch()
fetch.forEach { println(it) }
}
CaseBuilder์ ํ์ฉ
๋ค์๊ณผ ๊ฐ์ ์์์ ์์๋ก ํ์์ ์ถ๋ ฅํด๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
- 0 ~ 30์ด์ด ์๋ ํ์์ ๊ฐ์ฅ ๋จผ์ ์ถ๋ ฅ
- 0 ~ 20์ด ํ์ ์ถ๋ ฅ
- 21 ~ 30์ด ํ์ ์ถ๋ ฅ
@Test
fun testCase2() {
val rankPath = CaseBuilder()
.`when`(member.age.between(0, 20)).then(2)
.`when`(member.age.between(21, 30)).then(1)
.otherwise(3)
val result= query
.select(member.username, member.age, rankPath)
.from(member)
.orderBy(rankPath.desc())
.fetch()
for (tuple in result) {
val username = tuple.get(member.username)
val age = tuple.get(member.age)
val rank = tuple.get(rankPath)
println("username = $username age = $age rank = $rank")
}
}
Reference
728x90
'๐๏ธ Spring > QueryDsl' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[QueryDSL] @QueryProjection (feat. ํ๋ก์ ์ ) (0) | 2021.12.24 |
---|---|
[QueryDSL] ์์์ ๋ฌธ์ ๋ํ๊ธฐ (Expressions.constant, concat) (2) | 2021.12.23 |
[QueryDSL] ์๋ธ ์ฟผ๋ฆฌ (0) | 2021.12.23 |
[QueryDSL] ์กฐ์ธ, ํ์น์กฐ์ธ (0) | 2021.12.23 |
[QueryDSL] GroupBy (0) | 2021.12.23 |