findAllUseCountTop1ByIsActiveOrderById(Boolean isActive)不会使用“ LIMIT 1”生成查询

时间:2018-12-30 23:42:31

标签: mysql hibernate jpa spring-data-jpa

JPA为什么不对查询应用“ LIMIT 1”? 我试图在SpringBoot应用程序中编写一个存储库函数,以从顶部获得第一个结果,其中按ID排序时“ isActive”为TRUE。此函数生成的查询不包含“ LIMIT 1”,这将返回多个结果,并且由于“查询未返回唯一结果:4”异常而失败。我正在将Hibernate Core v5.3.7.Final和MySQL v8.0.12用作数据库。

生成的查询:

select phoneinfo0_.id as id1_0_, phoneinfo0_.Phone as Phone2_0_, phoneinfo0_.isActive as isActive3_0_, phoneinfo0_.useCount as useCount4_0_ from contactNumbers phoneinfo0_ where phoneinfo0_.isActive=1 order by phoneinfo0_.id asc;

返回的结果:

+--------+------------+--------------+--------------+
| id1_0_ | Phone2_0_  | isActive3_0_ | useCount4_0_ |
+--------+------------+--------------+--------------+
|      1 | 1111111111 |            1 |            0 |
|      2 | 9999999999 |            1 |            0 |
|      3 | 9000000000 |            1 |            0 |
|      4 | 2222222222 |            1 |            0 |
+--------+------------+--------------+--------------+

还请告诉我,如果ID是自动递增的主键,则是否需要“按ID排序”还是默认情况下在每次选择时完成?

1 个答案:

答案 0 :(得分:0)

尝试将其重命名为以下之一:

findTop1UseCountByIsActiveOrderById(Boolean isActive)

findFirstUseCountByIsActiveOrderById(Boolean isActive)