【问题标题】:Getting different results from Spring JPA query vs raw SQL in console从 Spring JPA 查询与控制台中的原始 SQL 获得不同的结果
【发布时间】:2020-04-11 06:41:27
【问题描述】:

当我在 MySQL 控制台中运行它时,我有以下 SQL 查询返回一个结果,正如预期的那样:

SELECT DISTINCT a.* FROM account a
INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE '%test@test.com%'
OR a.id IN (SELECT e.accountId FROM environment e WHERE e.externalId LIKE '%test@test.com%' 
    OR e.name LIKE '%test@test.com%')
OR c.email = 'test@test.com'

我在我的应用程序代码中使用了相同的查询,但返回的结果为零:

@Query(value = "SELECT DISTINCT a.* FROM account a INNER JOIN contact c ON a.id = c.accountId WHERE a.accountName LIKE %?1% OR a.id IN " +
    "(SELECT e.accountId FROM environment e WHERE e.externalId LIKE %?1% OR e.name LIKE %?1%) " +
    "OR c.email = ?1", nativeQuery = true)
List<Account> findAccountByKeyword(String keyword);

我看到正在生成以下 SQL,这对我来说很好:

select distinct account0_.id as id1_0_, account0_.createdBy as createdB2_0_, account0_.createdDate as createdD3_0_, account0_.lastUpdatedBy as lastUpda4_0_, account0_.updatedDate as updatedD5_0_, account0_.accountName as accountN6_0_, account0_.globalMessage as globalMe7_0_, account0_.isConsultingPartner as isConsul8_0_, account0_.isNonProfit as isNonPro9_0_, account0_.isSuspended as isSuspe10_0_, account0_.note as note11_0_, account0_.parentId as parentI12_0_, account0_.products as product13_0_, account0_.salesforceId as salesfo14_0_, account0_.type as type15_0_, account0_.typeShort as typeSho16_0_, account0_.usedProducts as usedPro17_0_

from account account0_ inner join contact contact1_ on (account0_.id=contact1_.accountId) 
where account0_.accountName like ? or account0_.id in (select environmen2_.accountId from environment environmen2_ where environmen2_.externalId like ?
    or environmen2_.name like ?)
or contact1_.email=?

您知道这里可能出了什么问题吗?我已经验证keyword 的值是正确的,所以我完全失去了我还能尝试的东西。关于原生 SQL 和 Spring 中的查询之间的不一致的其他问题都是关于日期类型的问题,但我什至没有在这里使用日期或任何特定方言的问题。

如果您需要更多信息,请告诉我,我会相应地编辑我的问题。

【问题讨论】:

  • 您的查询真的一样吗? Like '%test@test.com%' 在你的 Mysql 中,LIKE %?1% 在你的原生 SQL 中。我猜你在某个地方的参数之前和之后丢失了%
  • @FredvN 看起来你是对的。用CONCAT('%', ?1, '%') 替换就可以了。如果您想将其作为一个答案发布,很高兴接受作为答案。

标签: mysql sql jpa spring-data-jpa spring-data


【解决方案1】:

你的查询真的一样吗?就像你的 Mysql 中的 '%test@test.com%' 和你本机 SQL 中的 LIKE %?1% 。我猜你在某个地方丢失了参数之前和之后的 %。

like CONCAT('%', ?1, '%') 替换like %?1% 可能是解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2020-06-11
    • 2021-03-07
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多