
How to use Case Insensitive Search in Hibernate?

The Case Insensitive ignores the case of the latter. It Selects all the records of the table related to the given parameters.
Create hibernate configuration file (hibernate.cfg.xml) and save it in the same folder where you are going to save your source code.
Now create Persistent class Employee.javaâ??Hibernate uses the Plain Old Java Object (POJO) classes to map to the database table. Next create an util class as HibernateUtil.java
Here is your MainClass-
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
public class MainClass {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Criteria criteria =session.createCriteria(Employee.class);
criteria.add(Restrictions.like("name", "r%"));
List<Employee> employeeList = new ArrayList<Employee>();
employeeList = criteria.list();
Iterator it = employeeList.iterator();
while (it.hasNext()) {
Employee employee = (Employee) it.next();
System.out.println(employee.getName());
}
session.close();
}
}
Description: - Hibernate criteria is used here as alternative to HQL. The Criteria interface can be obtained using the Session.createCriteria() method.
criteria.add(Restrictions.like("name", "r%"));
//It selects all names that start with â??râ?? character without caring of case sensitivity.
Output:
Hibernate: select this_.emp_id as emp1_0_0_, this_.date_of_join as date2_0_0_, this_.name as name0_0_, this_.salary as salary0_0_ from employee this_ where this_.name like ? Ron Roxi
You can also Use Restrictions.eq().ignoreCase(). It checks equality, ignoring the case. Ex.
criteria.add(Restrictions.eq("name", "ron").ignoreCase());
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.