Hibernate GROUP BY Clause

In this tutorial you will learn how to use HQL GROUP BY clause.

Hibernate GROUP BY Clause

Hibernate GROUP BY Clause

In this tutorial you will learn how to use HQL GROUP BY clause.

GROUP BY clause in HQL is used as same as it is used in SQL. This clause is generally used with aggregate function and is used to return the results that may be grouped in one or more columns.

Example

Here I am giving a simple example which will demonstrate you how a HQL group by clause can be used. To achieve the solution of such problem at first I have created a table named salesorder with the fields 'id', 'price' and 'purchase'. Next created a POJO / Persistent class named SalesOrder to fetch the persistent object, a hibernate.cfg.xml file that the Hibernate can utilize it to create connection pool and the required environment setup, an salesorder.hbm.xml file to map the SalesOrder object with table salesorder. And finally create a simple java file into which we will use HQL group by clause. In this example we will calculate the price of each group of purchaser.

Complete Code

SalesOrder.java

package roseindia;

public class SalesOrder {
private int id;
private int price;
private String purchaser;

public SalesOrder()
{

}
public SalesOrder(int price, String purchaser)
{
this.price = price;
this.purchaser = purchaser;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getPurchaser() {
return purchaser;
}
public void setPurchaser(String purchaser) {
this.purchaser = purchaser;
}
}

salesorder.hbm.xml

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="SalesOrder" table="salesorder">
<id name="id" type="int" column="id" >
<generator class="assigned"/>
</id>
<property name="price">
<column name="price" />
</property>
<property name="purchaser">
<column name="purchaser" />
</property>
</class>
</hibernate-mapping>

HibernateGroupByClause.java

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 HibernateGroupByClause {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
{
Session session = null; 

try
{
try
{
Configuration cfg = new Configuration().addResource("roseindia/salesorder.hbm.xml");
cfg.configure();
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 groupByClause = session.createQuery("select so.purchaser, sum(so.price) from SalesOrder so group by so.purchaser");
List orderList = groupByClause.list();
System.out.println("Displaying data from table salesorder");
Iterator it = orderList.iterator(); //groupByClause.iterate();
System.out.println("purchaser \t price");
while(it.hasNext())
{
Object[] obj = (Object[])it.next();
System.out.println(obj[0] +"\t \t "+ obj[1]);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<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>
</session-factory>

</hibernate-configuration>

Output :

1. Data of table salesorder

2. When you will execute the java file HibernateGroupByClause.java (RightClick -> run as -> Java Application) output will be displayed on your console as :

Download Source Code