Home Hibernate Hibernate4 Hibernate count() Function


Share on Google+Share on Google+

Hibernate count() Function

In this tutorial you will learn how to use the HQL count() function

Hibernate count() Function

In this tutorial you will learn how to use the HQL count() function

count() function counts the maximum number of rows in a table however it doesn't count the null values of the specified column. This function can be simply written with the select clause, however it can be used in different ways, as

Query query = session.createQuery("select count(distinct gd.numOfGoodsOrder) from GoodsDealer gd");

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

for example :

count( [ distinct | all ] object | object.property)

count(*); also counts the null values properties.

Example :

Here I am giving a simple example where I will use the count() function with select query. After executing this example you will get the total number of rows. To do so in this example at first I have created a table named goodsdealer and inserted some value in their respected fields then created a POJO / Persistent class named GoodsDealer.java of which data members will be mapped to the database table by their respective fields using a mapping file created by the name GoodsDealer.hbm.xml. Then created a configuration mapping file by name hibernate.cfg.xml that provides information to the Hibernate to create a connection pool and required environment setup. Finally created a main class where I shall use the count() function with the select clause.

Complete Code

goodsdealer table

CREATE TABLE `goodsdealer` ( 
`goodsDealerId` int(15) NOT NULL, 
`orderedGoodsName` varchar(15) default NULL, 
`numOfGoodsOrder` int(20) default NULL, 
`priceOfGoods` int(10) default NULL 


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;

public class HibernateCountFunction {
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();
//Query query = session.createQuery("select count(gd.numOfGoodsOrder) from GoodsDealer gd");
//Query query = session.createQuery("select count(*) from GoodsDealer gd");
Query query = session.createQuery("select count(distinct gd.numOfGoodsOrder) from GoodsDealer gd");
Iterator count = query.iterate();
System.out.println("No. of rows : "+count.next()); 
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>


Output :

1. goodsdealer table

2. When you will execute the java file HibernateCountFunction.java (RightClick -> Run As -> Java Application) an output will be displayed to your console as :

Download Source Code


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 6, 2012

Ask Questions?    Discuss: Hibernate count() Function  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Ronak Soni
April 17, 2014

Thanxs.... It was very helpful.