Hibernate Restrictions Like Function
In this section, you will learn about Hibernate restriction like() or Restrictions.like() function with running example, code and its related output. Here, we will see the hibernate restrictions llike () method description and its running example.
like(): Hibernate criteria restriction like() method is used with Restrictions. Hibernate like() function similar to hibernate like MatchMode.EXACT. The hibernate Restrictions.like() function matched values to specified fields (table's column name) and given like query string.
Restrictions.like("field_name",like_query_string): Hibernate Restrictions.like() function takes two parameters, one for field and other one is like query sring. This function gives you all records which field_name=empName and like_query_string="Suraj Kumar". All results will come which match to "Suraj Kumar".
Now, We will see the running example of Restrictions.like() or like() function. The following example match the field_name = "empName" and like_query_string = "Suraj Kumar ". It gives you all results which empName like to "Suraj Kumar".
When execute the like query function then hibernte generate HQL as following:
Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_, this_.emp_sal as emp3_0_0_, this_.emp_expences as emp4_0_0_ from employee this_ where lower(this_.emp_name) like ?
package developerhelpway.hibernate.criteria.restriction;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import developerhelpway.hibernate.Employee;
public class RestrictionLikeExample {
/**
* @param args
*/
public static void main(String[] args) {
Session sess = null;
try{
SessionFactory sf = new Configuration().
configure().buildSessionFactory();
sess = sf.openSession();
Transaction tr = sess.beginTransaction();
Criteria criteria = sess.createCriteria(
Employee.class);
String matchString = "Suraj Kumar";
criteria.add(Restrictions.like(
"empName", matchString));
List<Employee> employees = criteria.list();
System.out.println("Get Employee which
match with :" + matchString);
for(Employee emp: employees){
System.out.println(
"Id: " + emp.getEmpId()
+ ", EmpName: " + emp.getEmpName()
+ ", EmpSal: " + emp.getEmpSal()
);
}
tr.commit();
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(sess != null){
sess.close();
}
}
}
}
|
Download Restriction like function Example
After running this example you will see the following output and SQL query which is generated by hibernate:
Hibernate: select this_.emp_id as emp1_0_0_, this_.emp_name as emp2_0_0_, this_.emp_sal as emp3_0_0_, this_.emp_expences as emp4_0_0_ from employee this_ where lower(this_.emp_name) like ?
OutPut:
