34

Is it possible to have a like in a where clause in a named query? I am trying to do the following but am getting exceptions

@NamedQuery(name = "Place.getPlaceForCityAndCountryName",
query = "SELECT p FROM Place p WHERE " +
        "lower(p.city) like :city and " +
        "lower(p.countryName) like :countryName");

I tried adding % as you would do in normal SQL but get exceptions compiling.

Any pointers greatly appreciated!

Thanks

RNJ
  • 15,272
  • 18
  • 86
  • 131

5 Answers5

66

You can't have the % in the NamedQuery, but you can have it in the value you assign the parameter.

As in:

String city = "needle";
query.setParamter("city", "%" + city + "%");
esej
  • 3,059
  • 1
  • 18
  • 22
14

You can also use CONCAT function

@NamedQuery(name = "Place.getPlaceForCityAndCountryName",
     query = "SELECT p FROM Place p WHERE " +
        "lower(p.city) like CONCAT(:city,'%')");
overmind1001
  • 141
  • 1
  • 2
7
@Query("select c from Curso c where c.descripcion like CONCAT(:descripcion,'%')")

List<Curso> findByDescripcionIgnoreCase(@Param("descripcion") String descripcion);
miken32
  • 42,008
  • 16
  • 111
  • 154
jean
  • 71
  • 1
  • 1
  • 1
    Welcome to Stack Overflow! While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Code-only answers are discouraged. – Ajean Dec 08 '16 at 01:13
1

With JPA only, without Spring Data Jpa, you must define named query without % and then include the pattern itself with % as a part of the value, as described by @esej:

  @NamedQuery(
    name = ParametersQueryOnEntityEntity.Queries.BY_LIKE,
    query = "SELECT e FROM SomeEntity e WHERE name LIKE :name")

With Spring's @Query you can define the query itself with % included and pass only a pattern value in the method:

  @Query("SELECT e FROM SomeEntity e WHERE name LIKE %:name%")
  List<SomeEntity> byLike(@Param(PARAM_NAME) String name);
Alexandr
  • 9,213
  • 12
  • 62
  • 102
0

If you are using positional parameters, you can use this way

@Query("select p from ABC p where p.name like CONCAT('%',?1,'%') ")
LMK IND
  • 472
  • 1
  • 5
  • 19