본문 바로가기

카테고리 없음

Spring querydsl 동적쿼리 Or 처리 할때

private BooleanExpression titleContain(String title) {
return (hasText(title)) ? board.title.contains(title) : null;
}

private BooleanExpression writerContain(String writer) {
return (hasText(writer)) ? board.writer.contains(writer) : null;
}

private BooleanExpression contentContain(String content) {
return (hasText(content)) ? board.content.contains(content) : null;
}

 

보통 이런식으로 식을 짜서

 

List<BoardDto> content = queryFactory
.select(new QBoardDto(board.id, board.title, board.writer, board.content, board.updatedTime))
.from(board)
.where(titleContain(boardSearch.title),

writerContain(boardSearch.writer)

)
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.orderBy(board.id.desc())
.fetch();

where에 넣으면 끝이다. 그런데 문제는 이렇게 해놓으면 모두 and처리가 된다.설사 where절 안에서 .or 을 써서 처리를 한다고 해도 .or에는 null이 들어오면 안되므로..

 

private BooleanBuilder searchCondition(String title, String content, String writer) {


BooleanBuilder booleanBuilder = new BooleanBuilder();
if (hasText(title)) {
booleanBuilder.or(board.title.contains(title));
}
if (hasText(content)) {
booleanBuilder.or(board.content.contains(content));
}
if (hasText(writer)) {
booleanBuilder.or(board.writer.contains(writer));
}


return booleanBuilder;
}

편하게 따로 메소드를 만들어 빌더만들어서 where안에 넣으면 간단히 해결되는 문제였다..