🧩 BooleanExpression

정의

BooleanExpressionQuerydsl에서 참/거짓 조건을 표현하는 타입이다. where() 절에 직접 넣을 수 있고, 조건 메서드를 분리해서 재사용할 때 유용하다.

동적 검색 조건을 메서드로 분리해두면 가독성과 재사용성이 좋아진다.

🧩 역할

  • 조건식을 객체로 표현한다
  • where() 절에 직접 사용할 수 있다
  • 조건 메서드를 분리해 재사용할 수 있다
  • 동적 쿼리에서 null 반환 패턴과 함께 사용한다

🛠 사용법

조건 메서드 분리

import com.querydsl.core.types.dsl.BooleanExpression;
import static com.myproject.domain.QUser.user;

public BooleanExpression isActive(Boolean isActive) {
    return isActive != null ? user.active.eq(isActive) : null;
}

여러 조건 조합

public BooleanExpression hasName(String name) {
    return name != null ? user.name.eq(name) : null;
}

public BooleanExpression isOlderThan(Integer age) {
    return age != null ? user.age.gt(age) : null;
}

public BooleanExpression buildQuery(String name, Integer age) {
    return hasName(name).and(isOlderThan(age));
}

where() 절 사용

List<User> result = queryFactory
        .selectFrom(user)
        .where(
                hasName(name),
                isOlderThan(age)
        )
        .fetch();

🧩 특징

  • 타입이 명확하다
  • 조건 메서드로 분리하면 재사용하기 좋다
  • null을 반환하면 where()에서 무시된다
  • 간단한 검색 조건에 적합하다

⚠️ 주의사항

  • null 반환 패턴을 활용해야 조건을 깔끔하게 생략할 수 있다.
  • 여러 조건을 무리하게 and()로 이어 붙이면 가독성이 떨어질 수 있다.
  • 복잡한 동적 조건은 BooleanBuilder가 더 편할 수 있다.
  • BooleanExpression은 Querydsl 전용 타입이다.

📌 정리

  • BooleanExpression은 Querydsl의 조건 표현 타입이다.
  • 조건을 메서드로 나눠 재사용할 때 유용하다.
  • 단순하고 타입 안전한 동적 조건 구성에 적합하다.

연결문서

댓글남기기