简体   繁体   English

JPA @Query 与 LIKE 和 UPPER %

[英]JPA @Query with LIKE and UPPER %

I am trying to run the following query in JPA hibernate @Repostiory:我正在尝试在 JPA hibernate @Repostiory 中运行以下查询:

@Query(value = "select city, state_code " +
          "from mv_city_state_center " +
          "where upper(city) like upper(:citycriteria)%",
          nativeQuery = true)
List<String> searchCityStateCenter(@Param("citycriteria") String cityCriteria);

In particular, the line like upper(:citycriteria)% .特别是like upper(:citycriteria)%的行。

The citycriteria is a partial string like 'pit' and I want to first capitalize it to PIT and then put it in the like statement eg. citycriteria是像'pit'这样的部分字符串,我想首先将其大写为PIT ,然后将其放在like的语句中,例如。 where upper(city) like PIT% - which would match to PITTSBURGH and PITTCAIRN for example. where upper(city) like PIT% - 例如匹配 PITTSBURGH 和 PITTCARN。

Hibernate accepts like pit% but when the upper is thrown in the mix, it fails for both: Hibernate 接受like pit%但当upper被混入时,两者都失败:

  • like upper(:citycriteria)%
  • like upper(:citycriteria%)

What is the correct syntax for this?什么是正确的语法? For now, I'm ensuring all caller methods just pass cityCriteria.toUpperCase() but would prefer if the query itself handled this so callers don't have to be concerned with it.现在,我确保所有调用者方法都只是通过cityCriteria.toUpperCase()但如果查询本身处理了这个,那么调用者不必关心它。

I also tried something like below from this guide to no avail.我还尝试了 本指南中的以下内容,但无济于事。

public interface AuthorRepository extends JpaRepository<Author, Long> {
 
    @Query("FROM Author WHERE UPPER(firstName) LIKE %?#{[0].toUpperCase()}%")
    List<Author> findByFirstNameContainingIgnoreCase(String firstName);
}

Can you try and concatenate the % with the value like so?您可以尝试将%与这样的值连接起来吗?

@Query(value = "select city, state_code " +
          "from mv_city_state_center " +
          "where upper(city) like upper(:citycriteria) + '%'",
          nativeQuery = true)
List<String> searchCityStateCenter(@Param("citycriteria") String cityCriteria);

This should work around the problem and treat upper like a function theoretically.这应该可以解决这个问题,理论上像 function 一样对待鞋面。

1 You are using a native query, why? 1 您正在使用本机查询,为什么?

2 You return a List but the projection has two columns (city, state_code)! 2 您返回一个列表,但投影有两列(城市、州代码)!

To concatenate two strings you can use concat:要连接两个字符串,您可以使用 concat:

@Query(value = "select city, state_code " +
          "from mv_city_state_center " +
          "where upper(city) like upper(concat(:citycriteria, '%'))"
          nativeQuery = true)
List<String[]> searchCityStateCenter(@Param("citycriteria") String cityCriteria);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM