Hibernate Criteria Count
Posted on: April 7, 2011 at 12:00 AM
In this tutorial you will learn, how to count no of records in a table

Hibernate Criteria Count

The Hibernate Criteria Count is used to count the numbers of records in a table. To Count a number of records in a table make a call to 'rowCount()' methods of projection class. Lets see how to use this rowCount() -

Session session = HibernateUtil.getSessionFactory().openSession();
	Criteria criteria = session.createCriteria(Student.class);
	criteria.setProjection(Projections.rowCount());
	List list = criteria.list();
An example of rowCount() is given below, please consider example

SampleInterfaceImp.java

package net.roseindia.main;

import java.util.List;

import net.roseindia.bean.Student;
import net.roseindia.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;

public class CriteriaCount {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Criteria criteria = session.createCriteria(Student.class);
		criteria.setProjection(Projections.rowCount());
		List list = criteria.list();
		System.out.println("No Of Record in table is - " + list.get(0));

	}
}

When you run this application it will display message as shown below:

Hibernate: select count(*) as y0_ from student this_
No Of Record in table is - 6

Download Complete Source Code

Related Tags for Hibernate Criteria Count:

Advertisements

Ads

 
Advertisement null

Ads