Hibernate Detached Criteria Subquery
In this section we will discuss how to write subqueries using Detached Criteria in Hibernate.
Hibernate Detached Criteria Subqueries :
By using Hibernate Criteria detached query you can write Hibernate subquries
without caring the scope of session.
Detached criteria query is very good alternate when the hibernate session is not
present.
By writing subqueries you can group, order and aggregate your resultant of
query. Subqueries executed before the query run.
Here is syntax of writing hibernate detached criteria subquery -
DetachedCriteria query = DetachedCriteria.forClass(Employee.class) .setProjection(Property.forName("salary").avg()); ....... ....... ...... employeeList = session.createCriteria(Employee.class).add( Subqueries.propertyGt("salary", query)).list();
Example : In this example we are showing how to write subquery using Criteria. Employee is our persistent class which maps employee table. In detachedCriteria query we are selecting the average salary. In subquery we are selecting records of employee whose salary is greater than average salary.
package net.roseindia.main; import java.util.*; import net.roseindia.table.Employee; import net.roseindia.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Property; import org.hibernate.criterion.Subqueries; public class DetachedCriteriaSubQuery { public static void main(String[] args) { DetachedCriteria query = DetachedCriteria.forClass(Employee.class) .setProjection(Property.forName("salary").avg()); SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); List<Employee> employeeList = new ArrayList<Employee>(); employeeList = session.createCriteria(Employee.class).add( Subqueries.propertyGt("salary", query)).list(); Iterator it = employeeList.iterator(); System.out.println(query.toString()); System.out.println("EmpId\tEmployee Name\tSalary\tDateOfJoin"); while (it.hasNext()) { Employee employee = (Employee) it.next(); System.out.print(employee.getId()); System.out.print("\t" + employee.getName()); System.out.print("\t\t" + employee.getSalary()); System.out.print("\t" + employee.getDateOfJoin()); System.out.println(); } session.close(); } }
Output :
Hibernate: select this_.emp_id as emp1_0_0_, this_.date_of_join as date2_0_0_, this_.name as name0_0_, this_.salary as salary0_0_ from employee this_ where this_.salary > (select avg(this_.salary) as y0_ from employee this_) EmpId Employee Name Salary DateOfJoin 1 Mandy 20000 2010-03-12 00:00:00.0 2 Som 20000 1999-06-22 00:00:00.0 4 Roxi 22000 2001-02-03 00:00:00.0 5 Rowdy 20000 2012-06-27 00:00:00.0 6 Linda 20000 2010-06-12 00:00:00.0