如何解决Spring Boot报错:query did not return a unique result: 4
问题原因
你的JPA Repository方法定义返回String类型,但查询语句select question from test_questions order by RAND() limit 4会返回4条字符串结果,JPA要求单个结果的方法只能返回1条数据,因此抛出query did not return a unique result: 4的异常。
而使用select *时正常,是因为此时返回的是实体对象列表,对应的方法应该是返回List<TestQuestions>(假设你的实体类名为TestQuestions),和查询返回的多条结果匹配,所以没有报错。
解决方案
根据你的需求,有两种修复方式:
方式一:获取4条question数据
把方法的返回类型改为List<String>,这样可以接收多条字符串结果:
@Query(nativeQuery = true, value = "select question from test_questions order by RAND() limit 4") List<String> getRandItems();
方式二:仅获取1条question数据
如果只需要单条随机数据,修改查询语句的limit为1,保持返回String类型:
@Query(nativeQuery = true, value = "select question from test_questions order by RAND() limit 1") String getRandItem();
内容的提问来源于stack exchange,提问作者Ghassan marwan
相关产品推荐
相关产品推荐

