Навигация
 
 
 
 
Languages
 
 

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.


Very good post, thanks a lot.

Very good post, thanks a lot.

Thanks a lot author

Thanks a lot author

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

Содержание этого поля является приватным и не предназначено к показу.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Syntax highlight code surrounded by the {syntaxhighlighter OPTIONS}...{/syntaxhighlighter} tags.

Подробнее о форматировании

CAPTCHA
Защита от спам сообщений
 
 
 
 
 
 
  • emmie
  • hooligan
  • cupuyc
  • ESoImk
  • LeKz
 
 
 
© 2006-2009 kobyleha.com