Search code examples
hibernatehqlhibernate-criteria

When is Criteria better in Hibernate?


Suppose, I need to count the number of rows in a database table using Hibernate based on some condition, I can use org.hibernate.criteria like the following.

@Service
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW)
public final class StateDAO implements StateService
{
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object rowCount(String id)
    {
        return sessionFactory.getCurrentSession()
              .createCriteria(State.class)
              .setProjection(Projections.rowCount())
              .add(Restrictions.eq("countryId", Long.parseLong(id)))
              .uniqueResult();
    }
}

It counts the number of rows based on the id being supplied via Spring.

This can also be achieved by using an HQL query like.

sessionFactory.getCurrentSession()
              .createQuery("select count(*) as cnt from State where countryId=:id")
              .setParameter("id", Long.valueOf(id).longValue())
              .uniqueResult();

Which one is better and usual (regarding performance and other things)?


Solution

  • In your case it's a matter of preference. Criteria API is type safe and maybe faster (you don't pay the price of parsing HQL). On the other hand HQL might be easier to read, especially for people with SQL background.

    The only place where you should use criteria API is when the query is dynamic, e.g. based on some input any subset of WHERE conditions can be selected. With HQL you will have to either build HQL from strings (looks bad) or have an exponential number of slightly different per-coined queries.