Spring & SpringBoot

Java/SpringBoot 게시판 기능 구현_Querydsl을 활용한 카테고리별 조회, 필터링

예령 : ) 2023. 10. 19. 20:00
💡 개발 환경
Java 11, Spring 2.7.X, Gradle 7.5, MySQL

 

[구현할 기능]

게시판에서의 카테고리별 목록 조회 기능 구현

 

현재 진행 중인 사이드 프로젝트 "펫팻"에서 맡고 있는 분양 게시판의 카테고리별 목록 조회 기능을 구현하고자 한다.

"펫팻" 분양 게시판 특성상 대분류 > 중분류 로 분류가 가능하다.

 

[Querydsl 을 사용한 이유]

1. 자동으로 쿼리를 작성해줌으로써 오류가 날 가능성을 줄여줌

2. 상황에 따라 다른 조건의 SQL을 작성해야하는 동적 쿼리를 다룰 때 용이

 


> RehomingServiceImpl

@RequiredArgsConstructor
@Service
public class RehomingServiceImpl implements RehomingService {

	private final RehomingRepository rehomingRepository;

    // 분양 게시글 카테고리별 목록 조회 (회원)
    @Override
    public RehomingPagingDto getCategoryListForMember(User user, Long categoryId, Long typeId, Pageable pageable) {
        Page<RehomingInfo> rehomingInfos = rehomingRepository.rehomingCategoryListForMember(user.getId(), categoryId, typeId, pageable);
        return new RehomingPagingDto(rehomingInfos);
    }

    // 분양 게시글 카테고리별 목록 조회 (비회원)
    @Override
    public RehomingPagingDto getCategoryList(Long categoryId, Long typeId, Pageable pageable) {
        return new RehomingPagingDto(rehomingRepository.rehomingCategoryList(categoryId, typeId, pageable));
    }
}

 

> RehomingService

public interface RehomingService {
    RehomingPagingDto getCategoryListForMember(User user, Long categoryId, Long typeId, Pageable pageable);
    RehomingPagingDto getCategoryList(Long categoryId, Long typeId, Pageable pageable);
}

> RehomingRepository

public interface RehomingRepository extends JpaRepository<Rehoming, Long>, RehomingRepositoryQuerydsl {
}

> RehomingRepositoryQuerydsl

public interface RehomingRepositoryQuerydsl {
    Page<RehomingInfo> rehomingCategoryListForMember(Long userId, Long categoryId, Long typeId, Pageable pageable);
    Page<RehomingInfo> rehomingCategoryList(Long categoryId, Long typeId, Pageable pageable);
}

> RehomingRepositoryImpl

public class RehomingRepositoryImpl implements RehomingRepositoryQuerydsl {
    private final JPAQueryFactory queryFactory;

    public RehomingRepositoryImpl(EntityManager em) {
        this.queryFactory = new JPAQueryFactory(em);
    }
   
    // 분양 글 카테고리별 목록 조회 (비회원)
    @Override
    public Page<RehomingInfo> rehomingCategoryList(Long categoryId, Long typeId, Pageable pageable) {
        QueryResults<RehomingInfo> results;
        results = queryFactory
                .select(
                        Projections.constructor(
                                RehomingInfo.class,
                                rehoming.rehomingId,
                                Expressions.as(
                                        select(image.filePath)
                                                .from(image)
                                                .where(image.postId.eq(rehoming.rehomingId),
                                                        image.postType.eq(PostType.REHOMING),
                                                        image.repImgNY.eq(true))
                                        , "rehomingImg"),
                                rehoming.user.id,
                                rehoming.user.profileImgPath,
                                rehoming.user.nickname,
                                rehoming.title,
                                rehoming.petName,
                                rehoming.category.categoryGroupName,
                                rehoming.type.petCategoryName,
                                rehoming.gender,
                                rehoming.status,
                                rehoming.postType,
                                rehoming.createdAt,
                                rehoming.updatedAt,
                                rehoming.viewCnt,
                                ExpressionUtils.as(
                                        select(likes.count())
                                                .from(likes)
                                                .where(likes.postId.eq(rehoming.rehomingId)),
                                        "likeCnt"),
                                ExpressionUtils.as(
                                        select(bookmark.count())
                                                .from(bookmark)
                                                .where(bookmark.postId.eq(rehoming.rehomingId)),
                                        "bookmarkCnt")
                        )
                )
                .from(rehoming)
                .leftJoin(rehoming.user, user)
                .where(rehoming.category.categoryGroupId.eq(categoryId),
                        rehoming.type.petCategoryId.eq(typeId))
                .orderBy(rehoming.createdAt.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
        List<RehomingInfo> content = results.getResults();
        long total = results.getTotal();

        return new PageImpl<>(content, pageable, total);
    }
}

 

where 절에 반려동물의 카테고리, 타입의 조건을 걸어 해당 조건에 맞는 게시물만 반환하도록 하였다.