Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case-insensitive search using Hibernate

People also ask

How do I ignore case in Hibernate query?

ilike(), which does a case-insensitive search. Just beware if you're switching from Eq to Like, you'll also get wildcards enabled, so things like underscores in oracle matching any character.

Is Hibernate query case-sensitive?

14.1.Queries are case-insensitive, except for names of Java classes and properties. So SeLeCT is the same as sELEct is the same as SELECT but org. hibernate.

Is HQl query case-sensitive?

HQL queries are case insensitive; however, the names of Java classes and properties are case-sensitive HQL is used to execute queries against database.

What is case-sensitive and case-insensitive in Java?

Java is a case-sensitive language, which means in code showData and showdata are two different variables. Java is case-sensitive because it uses a C-style syntax. In most programming languages, case sensitivity is the norm. Case-sensitive is useful because it lets you infer what a name means based on its case.


For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.

Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', '%fran%');
List results = crit.list();

Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', 'fran', MatchMode.ANYWHERE);
List results = crit.list();

If you use Spring's HibernateTemplate to interact with Hibernate, here is how you would do a case insensitive search on a user's email address:

getHibernateTemplate().find("from User where upper(email)=?", emailAddr.toUpperCase());

You also do not have to put in the '%' wildcards. You can pass MatchMode (docs for previous releases here) in to tell the search how to behave. START, ANYWHERE, EXACT, and END matches are the options.


The usual approach to ignoring case is to convert both the database values and the input value to upper or lower case - the resultant sql would have something like

select f.name from f where TO_UPPER(f.name) like '%FRAN%'

In hibernate criteria restrictions.like(...).ignoreCase()

I'm more familiar with Nhibernate so the syntax might not be 100% accurate

for some more info see pro hibernate 3 extract and hibernate docs 15.2. Narrowing the result set


This can also be done using the criterion Example, in the org.hibernate.criterion package.

public List findLike(Object entity, MatchMode matchMode) {
    Example example = Example.create(entity);
    example.enableLike(matchMode);
    example.ignoreCase();
    return getSession().createCriteria(entity.getClass()).add(
            example).list();
}

Just another way that I find useful to accomplish the above.