Hibernate Restriction not Function
In this section, you will learn about Hibernate restriction not() or Restrictions.not() function with running example, code and its output. Here, we will see the hibernate restrictions not() method descriptions and its running example.
Restrictions.not(Criteria expression): Hibernate Restrictions.not() function takes a Criteria (expression) object. Under this, we give a Restions.eq("empName", value). Put the criteria to match equal value. And finally add criteria not operation. It gives you all records which not matched to given expression.
Now, We will see the running example of Restrictions.not() or not() function. The following example match the field_name = "empName" and not matched object. It gives you all records which empSal is not "Suraj Kumar".
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 RestrictionNotExample {
/**
* @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 notEq = "Suraj Kumar";
criteria.add(Restrictions.not(Restrictions.eq(
"empName", notEq)));
List<Employee> employees = criteria.list();
System.out.println("Get Employee which not eq
to :" + notEq);
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 not 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 not (this_.emp_name=?)
OutPut:
