skip to Main Content

I am try to get some random data from the MySql data base,
in order to get that data I use the following query
@Query(nativeQuery = true,value = "select question from test_questions order by RAND() limit 4")
and I put that query in Jpa Repository interface and I made this custom Method
public String getRandItems();
but when I try to fetch data from postman it gives me this error
query did not return a unique result: 4

Note that it works for me when I use select * instead of select question but I do not want the whole data I just want the question column.

3

Answers


  1. You are limitting the result to 4 rows, so you should return a List of Strings instead of a simple String as result:

    public List<String> getRandItems();
    
    Login or Signup to reply.
  2. Yes as it is returning more than one result so it can store it in a single string you can change your method signature from
    public String getRandItems();

    To :
    public List<String> getRandItems();

    So it accepts all the results

    Login or Signup to reply.
  3. You are limiting the result to 4 rows, so you should return a List of Strings instead of a simple String as result:

    public List<String> getRandItems();
    

    or you can limit the result by 1 to get only one string:

    @Query(nativeQuery = true,value = "select question from test_questions order by RAND() limit 1")
    

    Look at the error it says that it did not return unique result because it is returning more the one result which does not matching with the method return type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search