Case-insensitive equals using Hibernate Criteria

Viewed 95060

I've seen Restrictions.ilike('property', '%value%'), but would like to generate SQL like: lower(property) = 'value'. Any ideas?

I used:

Restrictions.eq("email", email).ignoreCase()

since Expression is deprecated. The SimpleExpression will call toLowerCase() on the value, so it is not necessary to do it beforehand.

See: SimpleExpression source

7 Answers

Be careful of using ilike because it would allow someone to enter things like "test%" and match. I use the following to do a case-insensitive equal in one app:

...
Criteria crit=session.createCriteria(Event.class);
crit.add(Expression.eq("rsvpCode","test1").ignoreCase());
...

I'm not absolutely sure, but when you use Restriction.eq you obtain a SimpleExpression object, and that object suppports an ignoreCase() operation which I've never tried using but sounds like it could make a difference.

Kudos to Hibernate for not documenting what this method actually does.

If requirement is lower(property) = 'value' than best way is to use Restrictions.eq with ignoreCase() instead of using ilike cuz here the exact value is know. ilike is beneficial to search a pattern or when we are not aware of the exact value. Only problem with ignoreCase() is, it will not restrict your results to lower case and also include results with other cases , but i think is is the only available option hibernate offers.

 Criteria criteria = session.createCriteria(ClassName.class);
 criteria.add(Restrictions.eq("PROPERTY", propertyName).ignoreCase()).uniqueResult();

Now if I understand your question correctly, your db has these values: ABC, abc, aBC, aBc...and so on, you want to convert them to lower case and then compare with some value say "ABC" or "abc". YOu can do this by further processing the list you got.

You can save this result in a list.

List<ClassName> listOfAllMatches =  criteria.list(); // gives all matched results (ABC, abc, aBC, aBc)



List<ClassName> finalResult = listOfAllMatches.stream().map(x -> x.getPropertyName().toLowerCase()).filter(y ->y.getPropertyName()== value).collect(Collectors.toList());

//convert this field to lower case using map() and filter your results with filter() function.

YOU can further add this list to Criteria and process it.

You can use Criterion.ilike. For more information check this link.

crit(Restrictions.eq("firstName", firstName).ignoreCase()); works.

This did returns a SimpleExpression Object but It generates lower(firstname) query. So this works.

Related