【问题标题】:findAllUseCountTop1ByIsActiveOrderById(Boolean isActive) does not generate a query with "LIMIT 1"findAllUseCountTop1ByIsActiveOrderById(Boolean isActive) 不会生成带有“LIMIT 1”的查询
【发布时间】:2019-05-27 16:26:12
【问题描述】:

为什么 JPA 不对查询应用“LIMIT 1”? 我正在尝试在 SpringBoot 应用程序中编写一个存储库函数,以从顶部获取第一个结果,其中“isActive”在按 ID 排序时为 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 |
+--------+------------+--------------+--------------+

另外请告诉我“ORDER BY ID”是否是必要的,或者如果 ID 是主键自动递增,是否默认在每次选择时完成?

【问题讨论】:

    标签: mysql hibernate jpa spring-data-jpa


    【解决方案1】:

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

    findTop1UseCountByIsActiveOrderById(Boolean isActive)
    
    findFirstUseCountByIsActiveOrderById(Boolean isActive)
    

    【讨论】:

    • 嗨@KonstantinLabun 谢谢你这么快的回复。我已经尝试过了,当我从函数名称中删除 UseCount 时它可以工作。 JPA 直接忽略我要选择的列并选择整个表。我得到了我需要的东西,所以谢谢。只有一件事你知道如何只选择一个特定的列,或者为什么 JPA 选择整个表而不是只获取“UseCount”?
    • 方法名称是相当简单的事情。不确定它是否可以解决您的问题。尝试使用 JPQL:
    • 我刚刚读到它。我们显然不能。当我们想要选择特定的列时,我们必须使用@Query。我的解决方案是“findFirstByIsActiveTrueOrderById()”,因为我一直只想要活动对象并现在获取整个对象,因为它的其他值可以稍后使用。这也有帮助 [docs.spring.io/spring-data/jpa/docs/current/reference/html/….
    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 2015-04-17
    • 2012-01-18
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多