Hibernate Aggregate Functions

In this tutorial you will learn about aggregate functions in Hibernate

Hibernate Aggregate Functions

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

GoodsDealer.java

package roseindia;

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


public GoodsDealer()
{
super();
}
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;
}
}

GoodsDealer.hbm.xml

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

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

</hibernate-mapping>

HibernateSumFunction.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;
import org.hibernate.Transaction;

public class HibernateSumFunction {
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/GoodsDealer.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();
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();
System.out.println("totalPrice");
while(it.hasNext())
{
System.out.println(it.next());
}
t.commit();
}
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. goodsdealer table

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

Download Source Code