29

I am implementing an autocomplete functionality using Jquery, when I type the name, it fetches the record from the db, The records stored in db are mixture of capital & small letters. I have written a HQL Query which fetches me the records with case-sensitive, but I need to records irrespective of case. Here is the query,

List<OrganizationTB> resultList = null;
Query query = session.createQuery("from DataOrganization dataOrg where dataOrg.poolName   
like '%"+ poolName +"%'");
resultList =  query.list();    

Ex : If I have pool names, HRMS Data set, Hrms Data, Hr data etc... if I type HR or hr I need to get all the 3 records, which I'm not able to.

Please help...

Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64
madhu
  • 1,010
  • 5
  • 20
  • 38

2 Answers2

67

change your query to

"from DataOrganization dataOrg where lower(dataOrg.poolName)   
like lower('%"+ poolName +"%')"

for more information have a look 14.3 doc

Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64
  • 2
    Don't you think that `poolName.toLowerCase()` is a good choice over `lower('%"+ poolName +"%')"` for like expression, as it prevents extra overhead for HQL function conversion to DB specific function? – Arun Kumar Oct 28 '14 at 05:17
  • 1
    @ArunKumar i think if you `poolName.toLowerCase()` then comparsion will be done at Java-Pojo, there will not be any SQL optimization where as in case of function `lower` there is possibility at dialect level to have SQL optimization and will consume less memory with less no. of objects fetched from database. – Jigar Parekh Oct 30 '14 at 05:17
16

A good solution is:

List<OrganizationTB> resultList = null;
Query query = session.createQuery("from DataOrganization dataOrg where lower(dataOrg.poolName) like lower(:poolName)");
query.setParameter("poolName", '%'+poolName+'%', StringType.INSTANCE);
resultList =  query.list();

So you protect your code from SQL injection

Vasile Bors
  • 656
  • 6
  • 14