Home > Software design >  How to avoid this error on Spring Boot: (query did not return a unique result: 4)
How to avoid this error on Spring Boot: (query did not return a unique result: 4)

Time:10-08

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.

CodePudding user response:

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();

CodePudding user response:

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

CodePudding user response:

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.

  • Related