오봉이와 함께하는 개발 블로그

Querydsl - 동적 쿼리(BooleanBuilder) 본문

BE/JPA

Querydsl - 동적 쿼리(BooleanBuilder)

오봉봉이 2022. 9. 18. 23:00
728x90

동적 쿼리 - BooleanBuilder 사용

  • 동적 쿼리를 해결하는 두가지 방식
    • BooleanBuilder
    • Where 다중 파라미터 사용

BooleanBuilder

@Test
void dynamicQuery_BooleanBuilder() {
    String usernameParam = "member1";
    Integer ageParam = 10;
    List<Member> result = searchMember1(usernameParam, ageParam);
    Assertions.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();
}

builder.and외에도 or, or not등도 가능하다.
또, where(builder)에도 and, or 등을 넣을 수 있다.

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=?

age가 null이 되어도 코드가 잘 실행된다

select
    member1
from
    Member member1
where
    member1.username = ?1


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=?

필수값 가정

BooleanBuilder builder = new BooleanBuilder()에 초기값이 무조건 필요하면(절대 null이 넘어오지 않도록 해야한다.)
아래와 같이 작성할 수도 있다.

private List<Member> searchMember1(String usernameCond, Integer ageCond) {
    BooleanBuilder builder = new BooleanBuilder(member.username.eq("member1"));

    // if (usernameCond != null) {....} 가 빠짐.
    if (ageCond != null) {
        builder.and(member.age.eq(ageCond));
    }
    return queryFactory
            .selectFrom(member)
            .where(builder)
            .fetch();
}
인프런 김영한 지식공유자님 강의 : 실전! Querydsl
728x90
Comments