Home Hibernate Hibernate4 Hibernate avg() Function

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate avg() Function

Advertisement
In this tutorial you will learn about the HQL aggregate avg() function in hibernate.

Hibernate avg() Function

In this tutorial you will learn about the HQL aggregate avg() function in hibernate.

An avg() function in HQL performs the calculation on numeric value properties and returns an average value of that properties. An avg() function can be simply written with the select clause as :

select avg(numeric_Property_Name) from ClassName

Hibernate allows the different keywords as the SQL to be written with the avg() function.

for example : avg( [ distinct | all ] object.property )

Example :

Here an example is being given that will demonstrate you how to embed the HQL avg() function in between your query. For creating the example in Hibernate we would be required a table with numeric column/s onto which you have to apply this function. Then we will required a java class called a POJO/ Persistent class which objects will be mapped with this table. And a mapping file to map the class object with table, a configuration mapping file that will provide information to the Hibernate to create a connection pool and required environment setup. Then finally we will required a main class where we will write our query and many more works like obtaining a configuration, adding a class-table mapping file, creating and obtaining a session etc. So at first I have created a table named goodsdealer with the fields 'goodsDealerId (int, pk)', 'orderedGoodsName (varchar)', 'numOfGoodsOrder (int)', 'priceOfGoods (int)' with some records, 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, a GoodsDealer.hbm.xml file to map GoodsDealer object with table goodsdealer. And finally create a simple java file into which we will use the avg() function with select clause for getting the average value of the numeric properties.

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>

HibernateAvgFunction

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 HibernateAvgFunction {
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();
Query query = session.createQuery("select avg(gd.numOfGoodsOrder*gd.priceOfGoods) from GoodsDealer gd");
List avg=query.list();
Iterator it = avg.iterator();
System.out.println("avgPrice");
while(it.hasNext())
{
System.out.println(it.next());
}
}
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 HibernateAvgFunction.java (RightClick -> RunAs ->Java Application) output will be displayed on your console as :

Download Source Code

Advertisements

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

Discuss: Hibernate avg() Function  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com