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