Case-insensitive equals using Hibernate Criteria
Expression is now deprecated. Use Restrictions instead ...
crit(Restrictions.eq("firstName", firstName).ignoreCase());
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());
...
As Andy's answer suggests, this for case-insensitive searches but it is also works through to Hibernate version 4.1:
crit(Restrictions.eq("firstName", firstName).ignoreCase());
Versions 4.1.1 and later of Hibernate do not support the ignoreCase()
method on Restriction.eq()
. For that, we have to use ilike
with MatchMode
.
Criteria crit = session.createCriteria(ENTITY.class);
crit.add(Restrictions.ilike('PROPERTY NAME', 'VALUE', MatchMode.ANYWHERE));
As an example, for a USER entity with id, name, surname properties, a case-insensitive search based on name will be:
Criteria crit = session.createCriteria(USER.class);
crit.add(Restrictions.ilike('name', 'Satyam', MatchMode.ANYWHERE));
This will return all results, case insensitive.
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.