JpaRepository를 인터페이스에 상속하면 기본적인 메서드들 (ex. findbyid, findAll) 을 제공하지만, 디테일한 데이터를 쿼리하기 위해서는 내가 직접 작성할 필요가 있었다.
처음에는 다음과 같이 메서드들을 나눠서 작성했었다.
CustomPostRepositoryImpl.java
@Override
public Page<Post> findAllPost(Pageable pageable) {
List<Post> content = jpaQueryFactory
.selectFrom(qPost)
.orderBy(qPost.createAt.desc())
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();
JPAQuery<Long> count = getCount();
return PageableExecutionUtils.getPage(content, pageable, () -> count.fetchOne()); //count쿼리가 필요없을 때 사용하지 않는 최적화 적용.
//return new PageImpl(content, pageable, count);
}
@Override
public Page<Post> findUserPost(String userId, Pageable pageable) {
List<Post> content = jpaQueryFactory
.selectFrom(qPost)
.where(qPost.user.user_id.eq(userId))
.orderBy(qPost.createAt.desc())
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();
JPAQuery<Long> count = getCount();
return PageableExecutionUtils.getPage(content, pageable, () -> count.fetchOne());
}
이전 게시글에 repository의 구조를 변경한 바 있었다. 디테일한 커스텀 리포지토리 코드는 이 파일에 작성된다.
findAllPost 메서드는 모든 게시글을 가져오는 메서드이고, findUserPost는 유저 이름을 통해 게시글을 검색해 가져오는 메서드인데, 나는 여기서 검색하는 방식마다 메서드를 만들어야 한다는 점이 번거롭게 느껴졌다. 여기서 querydsl의 동적 쿼리에 대해 공부하게 되었다.
BooleanExpression이나 BooleanBuilder를 사용하면 일일이 이런 메서드를 만들 필요가 없었다.
@Override
public Page<Post> findPosts(Pageable pageable, String user_id, String title, String type, List<String> tags) {
List<Post> content = jpaQueryFactory
.selectFrom(qPost)
.where(UserIdEq(user_id), TitleEq(title), TypeEq(type), TagsEq(tags))
.orderBy(qPost.id.desc())
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();
JPAQuery<Long> count = getCount();
return PageableExecutionUtils.getPage(content, pageable, () -> count.fetchOne());
}
private BooleanExpression UserIdEq(String user_id){ return user_id.isBlank() != true ? qPost.user.user_id.eq(user_id) : null; }
private BooleanExpression TitleEq(String title){
return title.isBlank() != true ? qPost.title.eq(title) : null;
}
private BooleanExpression TypeEq(String type){
return type.isBlank() != true ? qPost.type.eq(type) : null;
}
findPosts는 게시글을 데이터베이스로부터 가져오는 심플한 메서드이다. 단, 여기서 where절을 통해 필터링 조건들을 넣는 것이다. BooleanExpression 타입의 반환값들을 where절에 넣으면 인식하게 되는데, 이 값이 null이면 그 부분은 아예 없는 셈 치고 건너 뛴다.
이것을 이용해 나는 검색하고자 하는 유저가 없다면(이건 유저이름 부분 매개변수를 공백으로 주는 걸로 정했다.) 그 조건은 null로 되어 아예 없는 조건이 되는 것이다.
이렇게 나뉘어졌던 메서드들을 하나의 메서드로 통합해냈다. 다음으로, 태그 필터링을 하는 코드를 작성하려 한다.
'Project > 9uin' 카테고리의 다른 글
springboot 사이드 프로젝트[9] : controller 작성 (0) | 2023.09.04 |
---|---|
spring boot 사이드 프로젝트[8] : 게시글 태그 필터링 (querydsl join) (0) | 2023.06.14 |
spring boot 사이드 프로젝트[6] : querydsl 설정 및 작성 (0) | 2023.05.26 |
spring boot 사이드 프로젝트[5] : service, repository 초기 작성 (0) | 2023.05.23 |
spring boot 사이드 프로젝트[4] : 도메인 엔티티, DTO 설계 및 특별한 패키지 구조 (0) | 2023.05.22 |