Latest Tutorials| Questions and Answers|Ask Questions?|Site Map

Home Hibernate Hibernate Count Query


Share on Google+Share on Google+

Hibernate Count Query

In this section we will show you, how to use the Count Query. Hibernate supports multiple aggregate functions.

Hibernate Count Query


In this section we will show you, how to use the Count Query. Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return an aggregate value (such as sum, average, and count) calculated from property values of all objects satisfying other query criteria. These functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and all values (except null values), respectively. Following is a list of aggregate functions with their respective syntax; all of them are self-explanatory.

count( [ distinct | all ] object | )

count(*) (equivalent to count(all ...), counts null values also)

sum ( [ distinct | all ]

avg( [ distinct | all ]

max( [ distinct | all ]

min( [ distinct | all ]

Here is the java code for counting the records from insurance table:

package roseindia.tutorial.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateHQLCountFunctions {

  public static void main(String[] args) {
  // TODO Auto-generated method stub

  Session sess = null;
  int count = 0;
  try {
  SessionFactory fact = new 
  sess = fact.openSession();
  String SQL_QUERY = "select 
count(*)from Insurance insurance group by 
  Query query = 
  for (Iterator it 
= query.iterate
(); it.hasNext();) {;
Total rows: " 
+ count);
  catch(Exception e){


Download this code.


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

log4j:WARN Please initialize the log4j system properly.

Hibernate: select count(*) as col_0_0_ from insurance insurance0_ group by insurance0_.ID

Total rows: 6


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: July 30, 2007

Related Tutorials

Discuss: Hibernate Count Query   View All Comments

Post your Comment

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