Case-insensitive equals using Hibernate Criteria

后端 未结 7 1472
旧时难觅i
旧时难觅i 2021-01-31 13:32

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

I used:

Restri         


        
相关标签:
7条回答
  • 2021-01-31 14:13

    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.

    0 讨论(0)
  • 2021-01-31 14:13

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

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

    0 讨论(0)
  • 2021-01-31 14:14

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

    0 讨论(0)
  • 2021-01-31 14:23

    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.

    0 讨论(0)
  • 2021-01-31 14:26

    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());
    ...
    
    0 讨论(0)
  • 2021-01-31 14:29

    Expression is now deprecated. Use Restrictions instead ...

    crit(Restrictions.eq("firstName", firstName).ignoreCase());
    
    0 讨论(0)
提交回复
热议问题