Hibernate Restriction And function
In this section, you will learn about Hibernate restrictions and() function with running example, code and its output. Here, we will see the hibernate restrictions and () method.
Restrictions.and(criteria, criteria): Hibernate and() method is used with hibernate restrictions. Hibernate and() function takes two parameters as hibernate restrictions, It gives you all records with matched the given criteria.
Now, We will see the running example of Restrictions.eq() or eq() function. The following example first criteria as field_name = "empName" and value = "Birendra Kumar". And second criteira as field_name = "empSal" and value = 12050.0 . It gives you all results which matched both criteira.
The following example gives you records which name is "Birendra Kumar" and salary is 12050.0.
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 RestrictionAndExample {
/**
* @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);
criteria.add(Restrictions.and(Restrictions.eq("empName"
, "Birendra Kumar"), Restrictions.eq("empSal", 12050.0)));
List<Employee> employees = criteria.list();
System.out.println("Get Employee which name is
Birendra Kumar and salary is 12050.0 :");
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 And 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_name=? and this_.emp_sal=?)
OutPut:
