Search code examples
springhibernatejpajpql

Java Spring, JPA - like expression with wildcard


I am struggling with creation of JPQL statement using Like expression in Java Spring application. My aim is to implement simple case insensitive search function.

My code, which should return a list of companies containing a keyWord in their name looks like this:

    List<Company> companies = em.createQuery("select cmp from JI_COMPANIES as companies where UPPER(cmp.name) LIKE :keyWord", Company.class)
            .setParameter("keyWord","%" + keyWord.toUpperCase() + "%").getResultList();
    return companies;

However, this query only works when my keyWord matches the name of company (Like statement is not used).

When testing the function above, I see in my console message from Hibernate:

Hibernate: select ... /* all my parameters */ ... where company0_.CMPN_NAME=?

It seems that my query is translated to cmpn_name='name' instead of using like expression.


Solution

  • It was my fault due to not understanding how Spring Data JPA library works.

    I have tried to create a custom implementation of myCompanyRepository (myCompanyRepository extends JpaRepository, CompanyRepositoryCustom).

    The code which I mentioned above was located in my CompanyRepositoryCustomImpl class which implements CompanyRepositoryCustom interface. However I used method name "findCompaniesByName(String name)". JPA automatically creates a query from this method name and my implementation is not used.

    Here is the link for Spring Data JPA reference