QueryDSL - 동적 쿼리

목차

동적 쿼리를 해결하는 두가지 방식

  • BooleanBuilder
  • Where 다중 파라미터 사용

동적 쿼리 - BooleanBuilder

BooleanBuilder 를 이용해 동적 쿼리를 작성할 수 있다.

@Test
public void dynamicQuery_BooleanBuilder(){
String usernameParam = "member1";
Integer ageParam = 10;

List<Member> result = searchMember1(usernameParam, ageParam);
assertThat(result.size()).isEqualTo(1);
}

private List<Member> searchMember1(String usernameCond, Integer ageCond){
BooleanBuilder builder = new BooleanBuilder();
if(usernameCond != null){
builder.and(member.username.eq(usernameCond));
}

if(ageCond != null){
builder.and(member.age.eq(ageCond));
}

return queryFactory
.selectFrom(member)
.where(builder)
.fetch();
}
/* select
member1
from
Member member1
where
member1.username = ?1
and member1.age = ?2 */ select
member0_.member_id as member_i1_1_,
member0_.age as age2_1_,
member0_.team_id as team_id4_1_,
member0_.username as username3_1_
from
member member0_
where
member0_.username=?
and member0_.age=?

동적 쿼리 - Where 다중 파라미터 사용

  • 메서드를 다른 쿼리에서도 재사용 할 수 있다.
  • 쿼리 자체의 가독성이 높아진다.
@Test
public void dynamicQuery_WhereParam() {
String usernameParam = "member1";
Integer ageParam = 10;

List<Member> result = searchMember2(usernameParam, ageParam);
assertThat(result.size()).isEqualTo(1);
}

private List<Member> searchMember2(String usernameCond, Integer ageCond) {
return queryFactory
.selectFrom(member)
// where 에 null 값이 전달 되면 조건을 무시한다.
.where(usernameEq(usernameCond),
ageEq(ageCond))
.fetch();
}

private Predicate usernameEq(String usernameCond) {
// 전달받은 usernameCond 파라미터가 없을 경우 null 을 반환하도록 한다.
if (usernameCond == null) {
return null;
}
return member.username.eq(usernameCond);
}

private Predicate ageEq(Integer ageCond) {
if (ageCond == null) {
return null;
}
return member.age.eq(ageCond);
}
Share