I’m working on a Spring Boot application using Spring Data JPA, and I’m trying to create a repository method that retrieves a random list of questions from a Question table based on a specified category. I attempted to use the @Query annotation for this purpose, but I’m encountering an error.
here is the code:
package com.example.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.model.Question;
@Repository
public interface QuestionDao extends JpaRepository<Question, Integer> {
List<Question> findByCategory(String category);
@Query(value = "SELECT q.id FROM question q Where q.category=:category ORDER BY RAND() LIMIT :numQ", nativeQuery = true)
List<Integer> findRandomQuestionsByCategory(String category, int numQ);
}
error:
MySQL: no viable alternative at input ‘SELECT * FROM Question q WHERE q.category = :category ORDER BY RAND() LIMIT :’
What I’ve Tried:
I used ORDER BY RANDOM() but switched to ORDER BY RAND() for MySQL compatibility.
what i am expecting:
A working JPA repository method that retrieves a specified number of random questions from the Question table based on the given category.
2
Answers
You can’t bind a placeholder to the
LIMIT
clause as you are doing. What you can do is to provide an implementation to thefindRandomQuestionsByCategory()
method and use the JPA repo methods to enforce a limit to the size of the result set.test this: