게시판 사이트 구현 중 게시판 내의 글을 검색하는 기능을 추가해야 했다.
쿼리문 생성을 위해 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;
}
}
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;
}