“select count” with Generics, Spring and Hibernate

In a recent project, we introduced Generics and Spring into an application. In developing the Generic DAO implementation I was trying to find a way to get a record count from the database. It’s a simple enough task with HQL or Spring’s JdbcTemplate.queryForInt(String sql), however the Generics made it a little tricky. The solution I came up with was using HibernateCallback. A reference to the persistent type is a member of GenericDAOHibernate as is the SessionFactory and an instance of Spring’s HibernateTemplate.

public class GenericDAOHibernate<T, PK extends Serializable> implements GenericDAO<T, PK> {

	/** log4j Logger for class GenericDAOHibernate */
	private static Logger logger = Logger.getLogger(GenericDAOHibernate.class.getName());

    private Class<T> persistentClass;

    private HibernateTemplate hibernateTemplate;

    @Autowired(required=true)
    private SessionFactory sessionFactory;

// [...]

@Override
public Class<T> getPersistentClass() {
    return persistentClass;
}

@Override
public int countAll() {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    List results = (List) hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            return session.createCriteria(getPersistentClass())
                .setProjection(Projections.rowCount())
                .list();
            }
        });

        // Here I use the Spring DataAccessUtils class to interpret the result set
        int result = DataAccessUtils.intResult(results)

        logger.debug("count retrieved: " + result;

        return result;
}

I also added another convenience method that uses the Example Criteria API so we can generate a count with a pre-configured Entity:

@Override
public int countByExample(final T exampleInstance)

    @SuppressWarnings({ "unchecked", "rawtypes" })
    List results = (List) hibernateTemplate.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            return session.createCriteria(getPersistentClass())
                .add(Example.create(exampleInstance))
                .setProjection(Projections.rowCount())
                .list();
            }
        });

        // Here I use the Spring DataAccessUtils class to interpret the result set
        int result = DataAccessUtils.intResult(results)

        logger.debug("count retrieved: " + result;

        return result;

I plan to package up some of the Generics code at some point and will post a link to download it or to a public source code repository.

Leave a Reply