Languages
 
 
 
 
Navigation
 
 
 
 
 
 

Hibernate. Count queries without HQL


I like to use Criteria class for making database queries. Its easy to use and easy to understand, much better then HQL queries. For example:

  @SuppressWarnings("unchecked")
  public List<LogAdd> findAddLogs(Long minLogID) {
    Criteria criteria = session.createCriteria(LogAdd.class);
    criteria.add(Restrictions.gt("id", minLogID));
    criteria.addOrder(Order.asc("date"));
    return criteria.list();
  }

Previously I had to use HQL only for writing 'count' type queries. Because just trying to get collection size mean to load all elements into memory from database and only then count them. Of course such kind of code isn't acceptable.

I have found new API method that can be used to create 'count' queries with Criteria class:

  public Integer countAddLogs(Long minLogID) {
    Criteria criteria = session.createCriteria(LogAdd.class);
    criteria.add(Restrictions.gt("id", minLogID));
    criteria.setProjection(Projections.rowCount());
    return (Integer) criteria.list().get(0);
  }

Look at Projections.rowCount(). This is what I'm talking about.

Maybe this is not a new and you are already familiar with this method, but I still decided to write short note about it.


Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>

More information about formatting options

 
 
 
 
 
 
  • hooligan
  • cupuyc
  • ESoImk
  • LeKz
  • Anton
 
 
 
© 2006-2008 kobyleha.com