【问题标题】:how to convert like %searchKey% to native query in spring boot jpa如何在spring boot jpa中将%searchKey%转换为本机查询
【发布时间】:2021-03-13 02:13:00
【问题描述】:

我正在尝试将以下查询转换为本机查询,当查询返回 2 个元组时,我得到了空列表

以下是查询:

SELECT 
  s.id AS shopID,
  s.shop_name AS shopName 
FROM
  shop s 
WHERE s.shop_name LIKE '%store%' ;

以下是我创建的方法,它返回空列表,而它应该发送包含两个对象的列表 (这是m仓库的方法)

    @Query(value = "SELECT \n" +
            "  s.id AS shopID,\n" +
            "  s.shop_name AS shopName \n" +
            "FROM\n" +
            "  shop s \n" +
            "WHERE s.shop_name LIKE %:searchKey%", nativeQuery = true)
    List<Object[]> buyerDashboardSearchSuggestion(@Param("searchKey") String searchKey);

查询结果

以下是我的邮递员要求

{
    "searchKey": "store"
}

依赖关系与db相关

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

【问题讨论】:

  • LIKE 和百分号周围缺少单引号。
  • 会不会像“WHERE s.shop_name 'LIKE' '%:searchKey%'” ??
  • 我尝试了这个“WHERE s.shop_name LIKE '%:searchKey%'”,但仍然得到了 0 个对象的列表
  • 应该可以的。检查您的参数,是否区分大小写?
  • 是的,但即使我保持大小写,如“商店”,我也会得到空列表。

标签: spring-boot jpa nativequery


【解决方案1】:

我怀疑%:searchKey%在原生查询中的组合,我认为%必须是参数的一部分。

@Query(value = "SELECT \n" +
            "  s.id AS shopID,\n" +
            "  s.shop_name AS shopName \n" +
            "FROM\n" +
            "  shop s \n" +
            "WHERE s.shop_name LIKE :searchKey", nativeQuery = true)
List<Object[]> buyerDashboardSearchSuggestion_internal(@Param("searchKey") String searchKey);

default List<Object[]> buyerDashboardSearchSuggestion(String searchKey) {
    return buyerDashboardSearchSuggestion_internal("%"+searchKey+"%");
    //todo escape special chars like % and _ in "searchKey"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 2020-04-15
    • 2013-10-08
    • 2019-01-22
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多