Home Hibernate Hibernate4 Hibernate Aggregate Functions


Share on Google+Share on Google+

Hibernate Aggregate Functions

In this tutorial you will learn about aggregate functions in Hibernate

Hibernate Aggregate Functions

In this tutorial you will learn about aggregate functions in Hibernate

In an aggregate functions values of columns are calculated accordingly and is returned as a single calculated value. Hibernate supports various useful Aggregate functions some of these are :

  1. avg(...), avg(distinct ...)
  2. sum(...), sum(distinct ...)
  3. min(...), max(...)
  4. count(*), count(...), count(distinct ...), count(all...)

As SQL in HQL arithmetic operators, concatenation, SQL recognized functions, distinct, keywords may be used, it depends upon the configured dialect, and they have the same meaning as in SQL.

Here I am giving a simple example of sum() function.

sum() function adds the values of numeric columns and returns a calculated single value.

Example :

Here an example is being given below where we will calculate the totalCost of Goods. To do so I have created a table named goodsdealer that contains the field 'goodsDealerId', 'orderedGoodsName', 'numOfGoodsOrder', 'priceOfGoods'. Then created a POJO / Persistent class named GoodsDealer 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 GoodsDealer.hbm.xml file to map GoodsDealer class with table goodsdealer. And finally create a simple java file into which we will use the sum function with select clause for adding the values of columns of the table.

Complete Code


package roseindia;

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

public GoodsDealer()
public GoodsDealer(int totalPrice, int priceOfGoods, int goodsDealerId, int numOfGoodsOrder, String orderedGoodsName)
this.totalPrice = totalPrice;
this.priceOfGoods = priceOfGoods;
this.goodsDealerId = goodsDealerId;
this.numOfGoodsOrder = numOfGoodsOrder;
this.orderedGoodsName = orderedGoodsName;
public int getTotalPrice() {
return totalPrice;
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
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-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="totalPrice">
<column name="totalPrice"/>
<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;
import org.hibernate.Transaction;

public class HibernateSumFunction {
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();
Transaction t = session.beginTransaction();
Query query = session.createQuery("select sum(gd.numOfGoodsOrder*gd.priceOfGoods) from GoodsDealer gd");
List sum=query.list();
Iterator it = sum.iterator();
catch(Exception e)



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



1. goodsdealer table

2. When you will execute the java file HibernateSumFunction (RightClick -> Run As -> Java Application) the output will be as :

Download Source Code


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  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.

Posted on: March 2, 2012

Related Tutorials

Ask Questions?    Discuss: Hibernate Aggregate Functions  

Post your Comment

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