Parameter in like clause JPQL Parameter in like clause JPQL java java

Parameter in like clause JPQL


If you do

LIKE :code

and then do

namedQuery.setParameter("code", "%" + this.value + "%");

Then value remains free from the '%' sign. If you need to use it somewhere else in the same query simply use another parameter name other than 'code' .


I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.

To workaround I use JPQL CONCAT function (this code emulate start with):

@Repositorypublic interface BranchRepository extends JpaRepository<Branch, String> {    private static final String QUERY = "select b from Branch b"       + " left join b.filial f"       + " where f.id = ?1 and b.id like CONCAT(?2, '%')";    @Query(QUERY)    List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);}

I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html


You could use the JPA LOCATE function.

LOCATE(searchString, candidateString [, startIndex]): Returns the first index of searchString in candidateString. Positions are 1-based. If the string is not found, returns 0.

FYI: The documentation on my top google hit had the parameters reversed.

SELECT   eFROM   entity eWHERE  (0 < LOCATE(:searchStr, e.property))