메모장
JPA Pageable 이용한 페이징 처리 본문
Controller
@RestController
@RequiredArgsConstructor
@RequestMapping("/info")
public class InfoController {
private final ResponseService responseService;
private final NoticeService noticeService;
@GetMapping("/notice")
@ApiOperation("공지사항 목록 조회")
public CommonResult getNoticeList(@PageableDefault Pageable pageable, SearchCondition searchCondition) {
return responseService.getSingleResult(noticeService.getNoticeList(pageable, searchCondition));
}
}
Service
@Service
@RequiredArgsConstructor
public class NoticeService {
private final NoticeRepository noticeRepository;
public Page<NoticeDTO> getNoticeList(Pageable pageable, SearchCondition searchCondition) {
return noticeRepository.getNoticeList(pageable, searchCondition);
}
}
Repository
@Repository
public interface NoticeRepository extends JpaRepository<Notice, Long>, NoticeRepositoryCustom {
}
public interface NoticeRepositoryCustom {
Page<NoticeDTO> getNoticeList(Pageable pageable, SearchCondition searchCondition);
}
public class NoticeRepositoryImpl implements NoticeRepositoryCustom {
private final JPAQueryFactory queryFactory;
public NoticeRepositoryImpl(EntityManager em) {
this.queryFactory = new JPAQueryFactory(em);
}
@Override
public Page<NoticeDTO> getNoticeList(Pageable pageable, SearchCondition searchCondition) {
QueryResults<NoticeDTO> results = queryFactory
.select(new QNoticeDTO(
notice.inDate,
notice.noticeSeq,
notice.category,
notice.title,
notice.writerName,
notice.viewCount))
.from(notice)
.where(titleEq(condition),
contentEq(condition),
writerNameEq(condition),
notice.deleDate.isNull())
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.orderBy(notice.noticeSeq.desc())
.fetchResults();
List<NoticeDTO> content = results.getResults();
long total = results.getTotal();
return new PageImpl<>(content, pageable, total);
}
private BooleanExpression titleEq(SearchCondition condition) {
if (Strings.isBlank(condition.getCategory())) {
return null;
}
return condition.getCategory().equals("title") && Strings.isNotBlank(condition.getKeyword())
? notice.title.contains(condition.getKeyword()) : null;
}
private BooleanExpression contentEq(SearchCondition searchCondition) {
if (Strings.isBlank(condition.getCategory())) {
return null;
}
return condition.getCategory().equals("content") && Strings.isNotBlank(condition.getKeyword())
? notice.content.contains(condition.getKeyword()) : null;
}
private BooleanExpression writerNameEq(SearchCondition searchCondition) {
if (Strings.isBlank(condition.getCategory())) {
return null;
}
return condition.getCategory().equals("writerName") && Strings.isNotBlank(condition.getKeyword())
? notice.writerName.contains(condition.getKeyword()) : null;
}
}
'Java' 카테고리의 다른 글
BigDecimal (0) | 2023.01.05 |
---|---|
테스트 코드 기본 세팅 (0) | 2023.01.04 |
Rest Api 응답 (0) | 2022.12.26 |
Custom Exception 만들기 (0) | 2022.12.20 |
JPA 저장된 정렬 정보 이용하여 리스트 조회 (0) | 2022.12.07 |