728x90
QueryDSL์์ ๋์ ์ฟผ๋ฆฌ ์ฌ์ฉํ๊ธฐ
QueryDSL์์ ๋์ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
- BooleanBuiilder ์ฌ์ฉ
- Where ๋ค์ค ํ๋ผ๋ฏธํฐ ์ฌ์ฉ (๊ถ์ฅ)
BooleanBuilder
@Test
@DisplayName("BooleanBuilder ๋ฅผ ์ฌ์ฉํ ๋์ ์ฟผ๋ฆฌ")
fun testBooleanBuilder() {
//given
var usernameParam = "member1"
var ageParam = 10
val result: List<Member> = searchMember1(usernameParam, ageParam)
assertThat(result.size).isEqualTo(1)
}
private fun searchMember1(usernameCond: String?, ageCond: Int?): List<Member> {
val booleanBuilder = BooleanBuilder()
usernameCond?.let { booleanBuilder.and(member.username.eq(it)) }
ageCond?.let { booleanBuilder.and(member.age.eq(it)) }
return query
.select(member)
.from(member)
.where(
booleanBuilder
)
.fetch()
}
Where ์ ์ ๋ค์ค ํ๋ผ๋ฏธํฐ ์ฌ์ฉ
where ์กฐ๊ฑด์ ์ ๋ฌ๋๋ null ๊ฐ์ ๋ฌด์๋๋ ๊ฒ์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋๋ค.
@Test
@DisplayName("where ๋ค์ค ํ๋ผ๋ฏธํฐ๋ฅผ ์ฌ์ฉํ ๋์ ์ฟผ๋ฆฌ")
fun testWhereParam() {
//given
var usernameParam = "member1"
var ageParam = 10
val result: List<Member> = searchMember2(usernameParam, ageParam)
assertThat(result.size).isEqualTo(1)
}
private fun searchMember2(usernameCond: String?, ageCond: Int?): List<Member> {
return query
.select(member)
.from(member)
.where(
usernameEq(usernameCond),
ageEq(ageCond),
ageCond?.let { member.age.eq(it)}
)
.fetch()
}
private fun ageEq(ageCond: Int?): BooleanExpression? {
return ageCond?.let { member.age.eq(it)}
}
private fun usernameEq(usernameCond: String?): BooleanExpression? {
return usernameCond?.let { member.username.eq(it)}
}
๋ฉ์๋๋ฅผ ๋ค๋ฅธ ์ฟผ๋ฆฌ์์๋ ์ฌํ์ฉ ํ ์ ์์ผ๋ฉฐ, ์ฟผ๋ฆฌ ์์ฒด์ ๊ฐ๋ ์ฑ์ด ๋์์ง๋๋ค.
์กฐํฉ ์์
private fun allEq(usernameCond: String, ageCond: Int): BooleanExpression? {
return usernameEq(usernameCond)?.and(ageEq(ageCond))
}
Reference
728x90
'๐๏ธ Spring > QueryDsl' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[QueryDSL] @QueryProjection (feat. ํ๋ก์ ์ ) (0) | 2021.12.24 |
---|---|
[QueryDSL] ์์์ ๋ฌธ์ ๋ํ๊ธฐ (Expressions.constant, concat) (2) | 2021.12.23 |
[QueryDSL] CASE ๋ฌธ (0) | 2021.12.23 |
[QueryDSL] ์๋ธ ์ฟผ๋ฆฌ (0) | 2021.12.23 |
[QueryDSL] ์กฐ์ธ, ํ์น์กฐ์ธ (0) | 2021.12.23 |