-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: How Can I count the query results using a HQL query???
PostPosted: Fri Aug 31, 2007 1:53 pm 
Newbie

Joined: Fri Aug 17, 2007 1:45 pm
Posts: 9
Hi everybody:

I want to know how Can I count the query results with HQL language.
I retrieve a group of documents from the database using the hibernate's tricks for paging the results but I want to know how many documents satisfied that query, I can't do it with a sql query so I want to use a hql query to know how many documents satisfied the query, if I retrieve the whole collection of documents that satisfied the query I get a java heap exception.

this is my code:


String queryString = "from TblDocumentos as model where model." + property + "= ?";
Query queryObject = session.createQuery(queryString);
queryObject.setParameter(0, value);
results = queryObject.setFirstResult(offset * limitPage).setMaxResults(limitPage).list();


I would like to use something like thjs:

String queryString = "from COUNT(TblDocumentos) as model where model." + property + "= ?";


I hop you can help me.
Thanks
Greetings


Top
 Profile  
 
 Post subject:
PostPosted: Sun Sep 02, 2007 3:57 pm 
Newbie

Joined: Sun Sep 02, 2007 1:20 pm
Posts: 5
I'd suggest the following:

Code:
StringBuffer hql = new StringBuffer();

hql.append("from TblDocumentos as model where model.").append(property).append("=?");

Query query = session.createQuery(hql.toString());
query.setParameter(0, value);
results = query.setFirstResult(offset * limitPage).setMaxResults(limitPage).list();

hql.insert(0, "select count(*) ");
query = session.createQuery(hql.toString());
query.setParameter(0, value);
Number n = (Number) query.uniqueResult();

long count = n != null? n.longValue(): 0;

Yes, query.uniqueResult() may return null. It's the case when your statement does not match any rows.

_________________
-alf


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.