Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Restrictions.like and .ilike in Hibernate Criteria API

Tags:

Hibernate's Criteria API has Restrictions.ilike function which has the following contract:

A case-insensitive "like", similar to Postgres ilike operator

That's cool. But the same class also has like function, having much more vague contract:

Apply a "like" constraint to the named property

example

Criteria cr = session.createCriteria(Employee.class);  // To get records having fistName starting with zara cr.add(Restrictions.like("firstName", "zara%"));  // Case sensitive form of the above restriction. cr.add(Restrictions.ilike("firstName", "zara%")); 
like image 613
mindas Avatar asked Mar 01 '11 20:03

mindas


People also ask

What is restriction in hibernate criteria?

The Criteria interface makes it easy to selectively fetch the data on the basis of conditions in the select query. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method.

What is Criteria API in Hibernate?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.

What is difference between HQL and Criteria in hibernate?

HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.


2 Answers

The case-sensitivity of the like operator, in MySQL, depends on the type of the columns and on their collation (see http://dev.mysql.com/doc/refman/5.5/en/case-sensitivity.html).

Hibernate is "just" a layer on top of SQL. The contract of the like operator is to issue a SQL like operator. If you want it to be the same for MySQL and PostgreSQL, then choose the right types and collations in the database schemas. But Hibernate can't magically make all the databases use the same rules.

Design your application, choose and design your database so that the behavior you observe is the behavior you expect.

PS : but I agree that the javadoc of Hibernate is... perfectible.

like image 83
JB Nizet Avatar answered Sep 28 '22 03:09

JB Nizet


ilike will be doing a lower of your input value, and a lower of the column value e.g.

select * from table where lower(column) like lower(?)

like image 37
Tom Chamberlain Avatar answered Sep 28 '22 04:09

Tom Chamberlain