
What is criteria conjunction in Hibernate?

In Hibernate, Criteria Conjunction works as logical AND operator. conjunction() groups the expressions into a single expression. If all conditions are satisfied, it will return true otherwise false. Take a look of bellow example- Steps-
1)Copy library (jar file) of hibernate into your lib folder.
2)Create hibernate configuration file (hibernate.cfg.xml) and save it in the same folder where you are going to save your source code.
3)Now create Persistent class Employee.java?Hibernate uses the Plain Old Java Object (POJO) classes to map to the database table using annotations.
4)Next create an util class as HibernateUtil.java
5)Here is your MainClass-
package net.roseindia.main;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.roseindia.table.Employee;
import net.roseindia.util.ConnectionUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
public class HibernateConjunction{
public static void main(String []args){
SessionFactory sessionFactory = ConnectionUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.conjunction().add(Restrictions.eq("id",1))
.add(Restrictions.eq("name", "Ron"))
);
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();
}
}
Output : Hibernate: select this.empid as emp100, this.dateofjoin as date200, this.name as name00, this.salary as salary00_ from employee this_ where (this.empid=? and this_.name=?) Ron
Description: -Employee is table class mapped with employee table. In the example, there are two conditions to check. First id must be equal to 1 and name must be Ron. Restrictions.conjunction() combinedly check both conditions and return true if both expressions are true.
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.