how to convert like %searchKey% to native query in spring boot jpa

五迷三道 提交于 2021-01-07 02:47:25

问题


I'm trying to convert the following query to native query, I'm getting empty list while the query is returning 2 tuples

following is the query :

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

following is the method I've created which is returning empty list while it's supposed to send a list containing two objects (this is the method of m repository)

    @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);

result of query

following is my postman request

{
    "searchKey": "store"
}

dependencies are related to db are

        <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>

回答1:


I doubt the combination of %:searchKey% in a native query, I think % must be part of the parameter.

@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"
}


来源:https://stackoverflow.com/questions/65085720/how-to-convert-like-searchkey-to-native-query-in-spring-boot-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!