Hibernate Aggregate Functions(Associations and Joins)

This example tries to make understand about the aggregate function of Hibernate with the help of example.


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 Aggregate Functions(Associations and Joins)


This example tries to make understand about the aggregate function of Hibernate with the help of example. 

In Hibernate HQL queries are capable of returning the results of the aggregate functions on properties.  Collections can also be used with the aggregate functions with the select clause. Aggregate functions supports the following functions:

  • min(...), max(...), sum(...), avg(...).
  • count(*)
  • count(distinct...), count(all..), count(...)

The distinct and all keywords used above are identical as in SQL. 

A unidirectional one-to-many association on a foreign key is rarely required.

<?xml version="1.0" encoding="UTF-8"?>

 <!DOCTYPE hibernate-mapping
 PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"

 <class name="net.roseindia.Dealer">
  <id name="id" type="int">
 <generator class="increment"/>

  <property name="name" type="string"/>
  <bag name="product" inverse="true"
  <key column="did"/>
  <one-to-many class="net.roseindia.Product"/>


A unidirectional one-to-many association on a foreign key is rarely required.

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

 <class name="net.roseindia.Product">
  <id name="id" type="int">
 <generator class="increment"/>

  <property name="name" type="string"/>
  <property name="did" type="int"/>
  <property name="price" type="double"/>
  <many-to-one name="dealer" class="
"false" update="false"/>


In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

Here is the hibernate code:

package net.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;

public class AggregateFunctionExample {

 @param args
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  Session sess = null;
  SessionFactory fact = new 
  sess = fact.openSession();
  String sql_query = "select 
d.name,p.name,sum(p.price) as
 totalprice from Product 
p join p.dealer d group by p.name"
  Query query = sess.createQuery(sql_query);
+"Product Name\t"+"Price");
  for(Iterator it=
  Object[] row = (Object[]) it.next();
  catch(Exception e ){



log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, sum(product0_.price) as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id group by product0_.name

Dealer Name  Product Name  Price

Agrawal   Computer   23100.0

Ritu   HardDisk  2500.0

Agrawal   Keyboard   1500.0

Ritu  Laptop   200.0

Mohan   Mobile   15000.0

Mohan   PenDrive   200.0

Share on Google+Share on Google+

Hibernate Aggregate Functions(Associations and Joins)

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



Discuss: Hibernate Aggregate Functions(Associations and Joins)   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
November 30, 2011
Hibernate Join Query

Its for just kids.
jay singh
February 29, 2012
Assistance in Hibernate join hbm.xml file

Hi, I was learning Hibernate through this tutorial, but on Topic -36 -Hibernate Aggregate Functions, i am not sure how would the hbm file and the java class look like.I have put both Dealer and Product hibernate mapping in hbm file.I have also created POJO classes for Dealer & Product. But i am getting error - Could not find a getter for product in class roseindia.tutorial.hibernate.Dealer. Can you tell me how the hibernate mapping in hbm file would look like. Also tell me if the POJO classes would be just getters & setters or something else needs to be done. Thanks - Jay
October 9, 2013
Could I convert row[] to object property ?

there is no other elegant option to return the object? print row[1], row[2] is really ugly , could I convert row[1] to getName()?