Hibernate Detached Criteria Subquery

In this section we will discuss how to write subqueries using Detached Criteria in Hibernate.


Hibernate 5.3 features Hibernate 5 JPA Configuration Hibernate 5 persistence.xml example Hibernate 5 JPA Tutorial Hibernate and JPA Example How properties of a class are mapped to the columns of a database table in Hibernate? Hibernate 5 Annotations Maven dependency Hibernate 5 annotationconfiguration Doctype Hibernate-configuration 5 Hibernate 5 Dialect Hibernate 5 configuration dtd Hibernate 5 Hello World Getting started with Hibernate 5 Hibernate 5.2.10 jar Download Hibernate 5.2.10 Maven Dependency Hibernate 5 Maven Dependency Hibernate 5 native query example Hibernate 5 query deprecated When should you use Hibernate? What's new in Hibernate 5? How much time it takes to learn Hibernate? Hibernate envers custom revinfo table Hibernate 5 Envers Hibernate Envers get all revisions Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse? Examples of Hibernate Criteria Query

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)
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)

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("EmpId\tEmployee Name\tSalary\tDateOfJoin");
while (it.hasNext()) {
Employee employee = (Employee) it.next();
System.out.print("\t" + employee.getName());
System.out.print("\t\t" + employee.getSalary());
System.out.print("\t" + employee.getDateOfJoin());


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

Click here to download complete source code

Share on Google+Share on Google+

Hibernate Detached Criteria Subquery

Posted on: August 7, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Hibernate Detached Criteria Subquery  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
January 18, 2013
subquery projection

I have 3 tables that I need to join: TableA, TableB and TableC. TableA is totally standalone, but TableB and TableC are related via one-to-many mapping (yay!) Here's my working join using Criteria API. DetachedCriteria tableBnCJoin= DetachedCriteria.forClass(TableB.class); tableBnCJoin.setProjection(Projections.property("tableBEmployeeId")); Criteria tableACriteria = getSession().createCriteria(TableA.class); criteria.add(org.hibernate.criterion.Property.forName("tableAEmployeeId").in(tableBnCJoin)); criteria.setProjection(Projections.projectionList() .add(Projections.distinct(Projections.property("tableAEmployeeId"))) .add(Projections.property("tableAEmployeeName"))); That all works well, but now I need to return TableCEmployeeAddress from TableC. How do I add the column TableCEmployeeAddress returned? Do I add the projection to tabBnCJoin criteria or tableACriteria?