Samuel
Samuel

Reputation: 1

Hibernate criteria.list bad results with quotes and accents

I'm using hibernate 3.6 and i'm having problems using criteria.list. I need search words with quotes or accents like "d'eau" or "d´eau". My code is something like this:

Criteria criteria;
criteria.add(Restrictions.ilike("nameParam", "d''eau", MatchMode.ANYWHERE));

I put two single quotes because i'm working with a sql server database. There are 2 single quotes because single quote escapes with another single quote. The statement has 0 results, but if I execute the sql statement printed in the log in the sql server client, I get 120 results aprox.

Testing with HQL and the same sql statement. I get this:

String hqlQuery = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like '%d''eau%')";
List qwer = getEntityManager().createQuery(hqlQuery).getResultList();
System.out.println("qwer.size() -> " + qwer.size());

String hqlQuery2 = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like :param)";
List qwer2 = getEntityManager().createQuery(hqlQuery2).setParameter("param", "%d''eau%").getResultList();
System.out.println("qwer2.size() -> " + qwer2.size());

This code print:

qwer.size() -> 120
qwer2.size() -> 0

And I don't understand why this happens. Sorry if my english is bad

Upvotes: 0

Views: 1789

Answers (1)

JB Nizet
JB Nizet

Reputation: 692073

You don't need to escape single quotes in your parameters. That's the whole point of using parameters (in Hibernate and, behind the scenes, in the JDBC prepared statements): the JDBC driver escapes everything that needs to be escaped for you.

You take what comes from the UI layer as is and stuff it into parameters, everything isproperly escaped by the driver, and you don't risk any SQL injection attack.

Upvotes: 1

Related Questions