The example below show how to get total row count using the Projections.rowCount()
. The result of this query will be a single object of Integer
that contains the result of executing an SQL select count (*) command.
package org.kodejava.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import org.kodejava.hibernate.model.Track;
import java.util.List;
public class ProjectionsCountDemo {
public static Session getSession() throws HibernateException {
String cfg = "hibernate.cfg.xml";
SessionFactory sessionFactory = new Configuration().configure(cfg)
.buildSessionFactory();
return sessionFactory.openSession();
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try (Session session = getSession()) {
Criteria criteria = session.createCriteria(Track.class)
.setProjection(Projections.rowCount());
List<?> result = criteria.list();
if (!result.isEmpty()) {
Long rowCount = (Long) result.get(0);
System.out.println("Total records: " + rowCount);
}
}
}
}
Maven Dependencies
<dependencies>
<!-- https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.6.9.Final/hibernate-core-5.6.9.Final.jar -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.9.Final</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.29/mysql-connector-java-8.0.29.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
Hi,
Is there any other neat method?
session.createCriteria()
is deprecated, so I have some concerns using it.Hi Dybuk,
You can use the JPA Criteria API as the replacement for the deprecated Hibernate API.
List result = criteria.list();
is not the correct way.Instead, use as following.
Long rowCount = (Long) criteria.uniqueResult();
PS: Not related to this post
Hi,
There is a “Views: 8,799” on this page, could you point me to an article which has some information on how to manage views on a UI screen, if you already have one or provide some information on how it could be done.
Thanks