수많은 시도..
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);
}
'부트캠프 TIL' 카테고리의 다른 글
23.03.19 @RequiredArgsConstructor @AllArgsConstructor , final 키워드 (0) | 2023.03.20 |
---|---|
23.03.10 controller에 갯수와 종류가 다른 param를 가진 같은 요청 종류 method 두 개 : cannot map ~ method (0) | 2023.03.10 |
23.02.24 UnsatisfiedDependencyException at ConstructorResolver.java:800 (0) | 2023.02.24 |
23.02.14 git 오류 일기 (0) | 2023.02.14 |
23.01.13 쿠키 옵션 (0) | 2023.01.13 |