Hibernate. How to Count Records

Easy as ABC, you may answer, and you will be absolutely right! It is not rocket science, yet some code looks quite complicated to complete this simplest task.

Today I watched a new episode of the Bones tv show and browsed some open source code. I found the following method:

public int getCount(Class clazz) {
	Integer rowCount  = new Integer(0);
	Criteria criteria = getCurrentSession().createCriteria(SomeEntity.class);

	List results = criteria.list();

        if(results != null && !results.isEmpty()){
        rowCount = results.size();
	} else {
		rowCount = new Integer(0);
	return rowCount;

Okay, 11 “readable” lines of code so far. I wouldn’t discuss the code style. Let’s just re-factor it a little bit.

How can we count records in Hibernate more appropriately? Let’s consider the following method:

public int getCount(Class clazz) {
	Criteria criteria = getCurrentSession().createCriteria(SomeEntity.class);
	Object result = criteria.setProjection(Projections.rowCount()).uniqueResult();

	return (null == result) ? 0 : ((Number) result).intValue();

Looks a little bit neatly, doesn’t it? Importantly, the re-written code doesn’t have a potential problem with the memory usage. Can you imagine to retrieve a few millions of entities just in order to call the size() method?

Category: Development, Hibernate, Java


Leave a Reply