Hibernate Restriction In Function
In this section, you will learn about Hibernate restrictions in() or Restrictions.in() function with running example, code and its output. Here, we will see the hibernate restrictions in () method functionality description with running example.
Restrictions.in("field_name",valiues): Hibernate in() function is used with hibernate restrictions. Hibernate Restrictions.in() function takes two parameters, one is property name or table's column name and other are list of values. It matches with gives column name and values which is list type. Results which are mached with given list of values for given column.
Now, We will see the running example of Restrictions.in() or in() function. The following example match the field_name = "empId" and values = (2,4,6) . It gives you all results which id's are equal to 2, 4 and 6.
package developerhelpway.hibernate.criteria.restriction;
import java.util.ArrayList;
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 RestrictionInExample {
/**
* @param args
*/
public static void main(String[] args) {
Session sess = null;
try{
SessionFactory sf = new Configuration().
configure().buildSessionFactory();
sess = sf.openSession();
List<Integer> empIds = new ArrayList<Integer>();
empIds.add(2);
empIds.add(4);
empIds.add(6);
Transaction tr = sess.beginTransaction();
Criteria criteria = sess.createCriteria(
Employee.class);
criteria.add(Restrictions.in("empId", empIds));
List<Employee> employees = criteria.list();
System.out.println("Get Employee which
match id with 2, 4, 6:");
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 ln 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 this_.emp_id in (?, ?, ?)
OutPut:
