본문 바로가기

부트캠프 TIL

23.02.25 키워드 검색 쿼리메서드 애썼다...

수많은 시도..

 

Repository

public interface QuestionRepository extends JpaRepository<Question, Long> {

//    다 똑같은 keyword parameter로 받아내서 questionTitle 또는 questionContents 또는 questionTrail 에서 keyword로 검색하는 쿼리 메서드
    Optional<Page<Question>> findByQuestionTitleContainingOrQuestionContentsContainingOrQuestionTrialContaining(String keyword1, String keyword2, String keyword3, Pageable pageable);

//    시도의 흔적들
//    @Query(value = "SELECT * FROM QUESTION AS Q WHERE Q.QUESTION_TITLE OR Q.QUESTION_CONTENTS OR Q.QUESTION_TRIAL LIKE %:keyword% LEFT OUTER JOIN VOTE_Q AS V ON Q.QUESTION_ID = V.QUESTION_ID ORDER BY V.VOTE_Q_COUNT DESC", nativeQuery =true)
//    Optional<List<Question>> findAllByKeyword(String keyword);

}

 

 

page를 list로 만들고 뭐고 엄청 시도해봤는데.. 결국 page로 받아왔다

 

Service

    @Transactional(readOnly = true)
    public Page<Question> findQuestionsBykeyword(int page, int size, String keyword) {

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "voteQ.voteQCount"));

        Optional<Page<Question>> optionalPage = questionRepository.findByQuestionTitleContainingOrQuestionContentsContainingOrQuestionTrialContaining(keyword, keyword, keyword, pageable);

        Page<Question> findPage =
                optionalPage.orElseThrow(() ->
                        new BusinessLogicException(ExceptionCode.QUESTION_NOT_FOUND));
        return findPage;
//        Optional<List<Question>> OptionalQuestions = questionRepository.findAllByKeyword(keyword);
//
//        List<Question> questionList = OptionalQuestions.orElseThrow(() ->
//                new BusinessLogicException(ExceptionCode.QUESTION_NOT_FOUND));
//
//        PageRequest pageRequest = PageRequest.of(page, size);
//
//        int start = (int) pageRequest.getOffset();
//        int end = Math.min((start + pageRequest.getPageSize()), questionList.size());
//
//        Page<Question> questionPage = new PageImpl<>(questionList.subList(start, end), pageRequest, questionList.size());
//
//        return questionPage;
//        return null;
    }

 

Controller

@GetMapping("/search")
public ResponseEntity searchQuestions(
        @RequestParam(value = "keyword") String keyword, @Positive @RequestParam int page,
        @Positive @RequestParam int size) {

    Page<Question> pageQuestions = questionService.findQuestionsBykeyword(page - 1, size, keyword);
    List<Question> questions = pageQuestions.getContent();
    return new ResponseEntity<>(
            new MultiResponseDto<>(questionMapper.questionsToQuestionResponseDtos(questions),
                    pageQuestions),
            HttpStatus.OK);
}