hasText()

박경희·2025년 2월 13일
0

공부를 해보자

목록 보기
28/40

hasText()란?

정의

  • hasText()는 SpringStringUtils 클래스에서 제공하는 메서드
  • 문자열이 null이 아니고, 공백("", " ")이 아닌 경우 true 반환
  • 즉, 값이 있는 경우만 쿼리에 추가하도록 설정하는 용도

예제

String username = "John";
System.out.println(StringUtils.hasText(username)); // true

String emptyText = " ";
System.out.println(StringUtils.hasText(emptyText)); // false

String nullText = null;
System.out.println(StringUtils.hasText(nullText)); // false

만약 hasText()를 사용하지 않는다면 아래와 같이 != null && !isEmpty() 조건을 사용할 수도 있다.

if (condition.getUsername() != null && !condition.getUsername().trim().isEmpty()) {
    builder.and(member.username.eq(condition.getUsername()));
}

하지만 hasText()를 사용하면 코드가 훨씬 깔끔하고 가독성이 좋아진다.


if 문이 하는 역할

if (hasText(condition.getUsername())) {
    builder.and(member.username.eq(condition.getUsername()));
}
  • username이 입력된 경우 → 해당 username
    을 검색 조건으로 추가
  • condition.getUsername() 값이 있으면 member.username = '입력된 값' 조건을 추가

0개의 댓글