[Spring] Querydsl 동적 쿼리 생성

서규범·2022년 12월 2일
0

게시판 사이트 구현 중 게시판 내의 글을 검색하는 기능을 추가해야 했다.
쿼리문 생성을 위해 querydsl을 사용하였으며, 검색은 제목, 내용, 제목+내용으로 검색이 가능하게끔 구현하였다.


PostGetDto.java

@Data
public class PostGetDto {

    private Long id;

    private String writer;

    private String title;

    private String content;

    private String movieLink;

    private String uploadFileName; // 사용자가 업로드한 이미지 파일명
    private String storeFileName; // 서버 내부 이미지 관리 파일명


    private LocalDateTime createdDate;
    private LocalDateTime modifiedDate;

    @QueryProjection
    public PostGetDto(Long id, String writer, String title, String content, String movieLink, String uploadFileName, String storeFileName, LocalDateTime createdDate, LocalDateTime modifiedDate) {
        this.id = id;
        this.writer = writer;
        this.title = title;
        this.content = content;
        this.movieLink = movieLink;
        this.uploadFileName = uploadFileName;
        this.storeFileName = storeFileName;
        this.createdDate = createdDate;
        this.modifiedDate = modifiedDate;
    }
}
  • 게시글 데이터를 조회하기 위한 DTO이다.
  • QueryProjection을 통해 compileQuerydsl 을 통해 Q클래스가 생성되도록 한다.

PostSearchCondition.java

@Data
@NoArgsConstructor
public class PostSearchCondition {

    private String title;
    private String content;
}
  • 검색 요청에 대한 매개변수를 담고 있는 클래스이다.

PostService.java

...


    public List<PostGetDto> search(PostSearchCondition condition) {
        return queryFactory
                .select(new QPostGetDto(
                        post.id,
                        post.writer,
                        post.title,
                        post.content,
                        post.movieLink,
                        post.uploadFileName,
                        post.storeFileName,
                        post.createdDate,
                        post.modifiedDate))
                .from(post)
                .where(containTitle(condition.getTitle()),
                        containContent(condition.getContent()),
                        post.deleteYN.eq(0))
                .fetch();
    }

    private BooleanExpression containContent(String content) {
        return StringUtils.hasText(content) ? post.content.contains(content) : null;
    }

    private BooleanExpression containTitle(String title) {
        return StringUtils.hasText(title) ? post.title.contains(title) : null;
    }
  • PostSearchCondition을 주입받아 동적으로 쿼리를 생성하고 있다.
  • 해당 함수를 실행 시킬 때, BooleanExpression을 통해 String에 값이 있을 경우와 없을 경우를 나누어 동작하게 된다.
  • post.content.contains(content)의 경우 content 값이 "검색"일 경우, "%검색%"에 해당하는 값을 DB에서 조회하는 것과 같다.
profile
하려 하자

0개의 댓글