Search code examples
hibernatefilteringsql-like

Hibernate - LIKE expression for case insensitive fitering


How can I use LIKE expression for case insensitive filtering in hibernate?

The corresponding entry in my hibernate file is:

<filter name="applicantNameFilter" condition="first_name LIKE :nameFilter"/>

Solution

  • Try this

    <filter name="applicantNameFilter" condition="first_name ILIKE :nameFilter"/>
    

    or

    <filter name="applicantNameFilter" condition="UPPER(first_name) LIKE UPPER(:nameFilter)"/>
    

    For Reference

    1. Using ILIKE:

      SELECT * FROM sometable WHERE textfield ILIKE 'value%';    
    2. Using Regexp operators (see Functions and Operators in the docs):

      SELECT * FROM sometable WHERE textfield ~* 'value';
    3. Using UPPER() or LOWER() to change the case of the field before comparison; this approach can be better than 1) or 2) because these functions may be indexed, and thus if you are doing a "begins with" or "exact match" search your query may be indexed:

      SELECT * FROM sometable WHERE UPPER(textfield) LIKE (UPPER('value') || '%');
    4. If most of your searches are "anywhere in field" searches on large text fields, I'd reccomend a look at the two "full text search" tools available in PostgreSQL, one in the /contrib of your source, the second from openFTS.org.

    This is java code

    User criteria as

    Criteria criteria = getSession().createCriteria(Person.class);
    criteria.add(Restrictions.ilike("first_name", first_name, MatchMode.ANYWHERE));
    criteria.list();