I\'ve seen Restrictions.ilike(\'property\', \'%value%\'), but would like to generate SQL like: lower(property) = \'value\'. Any ideas?
I used:
Restri
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.
crit(Restrictions.eq("firstName", firstName).ignoreCase());
works.
This did returns a SimpleExpression Object
but It generates lower(firstname)
query. So this works.
You can use Criterion.ilike. For more information check this link.
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.
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());
...
Expression is now deprecated. Use Restrictions instead ...
crit(Restrictions.eq("firstName", firstName).ignoreCase());