我有一种根据类别通过数据库进行搜索的方法,我选择使用 SpringJPa 派生查询。检查下面
Page<TriviaQuestion> findByCategoryOrCategory(String categoryOne, String categoryTwo, Pageable pageable);
这是正在使用的方法。 getTotalElements 的结果是 O,这不应该是。
public ResponseEntity<APIResponse> getQuizByTwoCategoryOnly(String categoryOne, String categoryTwo, int page, int size) {
Pageable pageable = PageRequest.of(page,size);
Page<TriviaQuestion> response = questionRepository.findByCategoryOrCategory(categoryOne,categoryTwo,pageable);
log.info("I retrieved {} entities",response.getTotalElements());
Set<QuizResponse> quizResponses = new HashSet<>();
for(TriviaQuestion question : response){
QuizResponse quizResponse = new QuizResponse();
quizResponse.setQuestion(question.getQuestion());
quizResponse.setCategory(question.getCategory());
quizResponse.setDifficulty(question.getDifficulty());
quizResponse.setAnswer(question.getCorrectAnswer());
Set<String> options = question.getIncorrectAnswer().stream().map(WrongAnswers::getWrongAnswers).collect(Collectors.toSet());
options.add(question.getCorrectAnswer());
quizResponse.setOptions(options);
quizResponses.add(quizResponse);
}
log.info("I am suppose to pass {} ", quizResponses.size());
return ResponseEntity.ok(new APIResponse(HttpStatus.FOUND,quizResponses,"Quiz questions based on to categories"));
}
我已经使用了本机查询,但我的数据库仍然没有结果
"SELECT * FROM TRIVIA_QUESTION" +
" WHERE " +
" CATEGORY =?1 OR CATEGORY =?2";
这是 Hibernate 生成的查询。
select tq1_0.id,tq1_0.category,tq1_0.correct_answer,tq1_0.difficulty,tq1_0.question from trivia_question tq1_0 where tq1_0.category=? or tq1_0.category=? limit ?,?
现在我尝试通过直接将这些查询放入我的数据库中来检查这些查询是否正确,并且它们产生了所需的结果。 这是我在mysql中使用的查询,与JPA生成的类似,我只是输入我自己的值。
select tq1_0.id,tq1_0.category,tq1_0.correct_answer,tq1_0.difficulty,tq1_0.question
from trivia_question tq1_0 where tq1_0.category= 'Science: Computers' or tq1_0.category= 'Politics' limit 0,15;
将您的参数放入列表中并使用它
Page<TriviaQuestion> findByCategoryIn(List<Category> categories, Pageable pageable);