Share on Google+Share on Google+

Hibernate Subqueries Example

In this tutorial you will learn about HQL subqueries.

Hibernate Subqueries Example

In this tutorial you will learn about HQL subqueries.

A query that is written within a databases supported query is called subquery. A subquery is surrounded by parentheses. Subqueries are generally written for solving the query result grouping, ordering, narrowing, and aggregating, that are used by where clause. Hibernate HQL also supports, if database supports subselect, subqueries within queries. for example :

from GoodsDealer gd where gd.numOfGoodsOrder =
(select max(gd.numOfGoodsOrder) from gd )

NOTE : Subselect / Subqueries are executed before the main query.

Example :

Here an example is being given below which will demonstrate you how to write HQL subquery within query. To do so at first we will required a database that supports the subselect query I have selected MySQL (you can choose as your choice) and then created a table named goodsdealer(goodsDealerId(int), orderedGoodsName(varchar), numOfGoodsOrder(int), priceOfGoods(int) ) then created a POJO / Persistent class class to fetch the persistent object, next created a hibernate.cfg.xml file that provides the information to the Hibernate to create connection pool and the required environment setup, then created a GoodsDealer.hbm.xml file to map class object with table goodsdealer. And finally create a simple java file into which we will write subquery within a query.

goodsdealer table

CREATE TABLE `goodsdealer` ( 
`goodsDealerId` int(15) NOT NULL, 
`orderedGoodsName` varchar(15) default NULL, 
`numOfGoodsOrder` int(20) default NULL, 
`priceOfGoods` int(10) default NULL 

package roseindia;

public class GoodsDealer {
private int goodsDealerId;
private int numOfGoodsOrder;
private int priceOfGoods;
private String orderedGoodsName;

public GoodsDealer()
public GoodsDealer(int priceOfGoods, int goodsDealerId, int numOfGoodsOrder, String 
this.priceOfGoods = priceOfGoods;
this.goodsDealerId = goodsDealerId;
this.numOfGoodsOrder = numOfGoodsOrder;
this.orderedGoodsName = orderedGoodsName;
public int getPriceOfGoods() {
return priceOfGoods;
public void setPriceOfGoods(int priceOfGoods) {
this.priceOfGoods = priceOfGoods;
public int getGoodsDealerId() {
return goodsDealerId;
public void setGoodsDealerId(int goodsDealerId) {
this.goodsDealerId = goodsDealerId;
public int getNumOfGoodsOrder() {
return numOfGoodsOrder;
public void setNumOfGoodsOrder(int numOfGoodsOrder) {
this.numOfGoodsOrder = numOfGoodsOrder;
public String getOrderedGoodsName() {
return orderedGoodsName;
public void setOrderedGoodsName(String orderedGoodsName) {
this.orderedGoodsName = orderedGoodsName;


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>



<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"

<hibernate-mapping package="roseindia">
<class name= "GoodsDealer" table="goodsdealer">
<id name= "goodsDealerId" type="int" column="goodsDealerId">
<!-- <generator class="increement"/>-->
<property name="numOfGoodsOrder">
<column name="numOfGoodsOrder"/>
<property name="orderedGoodsName">
<column name="orderedGoodsName"/>
<property name="priceOfGoods">
<column name="priceOfGoods"/>


package roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSubqueryExample {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
Session session = null;
Configuration cfg= new Configuration().addResource("roseindia/GoodsDealer.hbm.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
catch(Throwable th)
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
session = sessionFactory.openSession();
Query query = session.createQuery("from GoodsDealer gd where gd.numOfGoodsOrder = (select max(gd.numOfGoodsOrder) from gd )");
List<GoodsDealer> subQuery = query.list(); 
Iterator<GoodsDealer> it = subQuery.iterator();
System.out.println("goodsDealerId \t numOfGoodsOrder \t orderedGoodsName \t priceOfGoods");
GoodsDealer gd =;
System.out.println("\t"+gd.getGoodsDealerId()+" \t\t "+gd.getNumOfGoodsOrder()+" \t\t\t "+gd.getOrderedGoodsName()+" \t\t "+gd.getPriceOfGoods()); 

catch(Exception e)

Output :

Mar 5, 2012 4:49:45 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Mar 5, 2012 4:49:45 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select goodsdeale0_.goodsDealerId as goodsDea1_0_, goodsdeale0_.numOfGoodsOrder as 
numOfGoo2_0_, goodsdeale0_.orderedGoodsName as orderedG3_0_, goodsdeale0_.priceOfGoods as priceOfG4_0_ from 
goodsdealer goodsdeale0_ where goodsdeale0_.numOfGoodsOrder=(select max(goodsdeale0_.numOfGoodsOrder) from 
goodsdealer goodsdeale0_)

1. goodsdealer table

2. When you will execute the java file (RightClick -> Run As -> Java Application an output will be displayed on your console as :

Download Source Code


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

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate Subqueries Example  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image