
How do we count rows using criteria in hibernate?

Create hibernate configuration file (hibernate.cfg.xml) and save it in the same folder where you are going to save your source code.
Now create Persistent class ?Hibernate uses the Plain Old Java Object (POJO) classes to map to the database table. Here is the code of Employee.java ? Next create an util class as HibernateUtil.java Here is your MainClass-
package roseindia.application;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import roseindia.table.Employee;
import roseindia.util.HibernateUtil;
public class MainClass{
public static void main(String[] args) {
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
Session session=sessionFactory.openSession();
Criteria criteria=session.createCriteria(Employee.class);
criteria.setProjection(Projections.rowCount());
List list = criteria.list();
System.out.println("Number of employee : "+list.get(0));
}
}
Description: Hibernate criteria is used here as alternative to HQL. In general an application has a single sessionFactory. If you are using multiple databases then you must have sessionFactory for each database. SessionFactory is configured in your configuration file hibernate.cfg.xml.
Projections.rowCount() counts all the rows of your table.

Code:
Criteria criteria = this.getSession().createCriteria(User.class);
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
criteria.setMaxResults(10);
// First get the results without joining with the other tables
List<User> results = criteria.list();
// at this point the set roles is filled with proxies
// we'll now create and execute the join so these proxies are filled since we're still in the same session
getSession().createCriteria(User.class, "u")
.createAlias("u.roles", "r", CriteriaSpecification.LEFT_JOIN)
.list();
return results;
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.