Hibernate. Count queries without HQL

The comment you are replying to does not exist.
  Tagged

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.

Share this

Оставьте новый коментарий

CAPTCHA
Бот ты или человек?
 
© 2006-2010 kobyleha.com