Ghassan marwan
Ghassan marwan

Reputation: 11

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

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.

Upvotes: 1

Views: 1387

Answers (3)

Sk Nur Hasan
Sk Nur Hasan

Reputation: 61

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.

Upvotes: 1

Sumit
Sumit

Reputation: 407

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

Upvotes: 0

Simulant
Simulant

Reputation: 20122

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

Upvotes: 2

Related Questions