Hi all,
I'm having some trouble figuring out just how to get a total record count using a query with parameters and joining multiple tables. I've been through the forum hoping to find a solution but I can't put it all together.
I'm currently running Hibernate 2.1.2 and MySQL 4.0.15
I have a somewhat complex query where I'm joining multiple tables via assocation tables. The part that needs some background is in the pet.attributes table. This is an association table of pets to their attributes and I'm selecting all pets who have match to three attributes (reference_id's).
An example of this association table might look like:
Code:
+--------+--------------+
| pet_id | reference_id |
+--------+--------------+
| 1 | 3 |
| 1 | 198 |
| 1 | 219 |
| 2 | 5 |
| 2 | 96 |
| 2 | 198 |
+--------+--------------+
My query is defined as
Code:
SELECT pet
FROM Pet AS pet
INNER JOIN pet.client AS cl
INNER JOIN cl.clientToIdentity AS clid
INNER JOIN pet.identity AS ident
INNER JOIN pet.attributes AS rc
WHERE rc.referenceId IN (198, 219, 3) AND
LOWER(cl.accountId) LIKE LOWER(:accountId)AND
clid.type=:clientType AND
LOWER(clid.identity.firstname) LIKE LOWER(:ownerFirstName) AND
LOWER(clid.identity.lastname) LIKE LOWER(:ownerLastName) AND
ident.type=:petType AND
LOWER(ident.identity.firstname) LIKE LOWER(:petFirstName) AND
LOWER(ident.identity.lastname) LIKE LOWER(:petLastName)
GROUP BY pet.petId
HAVING COUNT(pet.petId)=3
and via hibernate I use
Code:
Query query = session.createQuery(querySearch);
query.setParameter("accountId", accountId+"%");
query.setParameter("clientType", "self");
query.setParameter("ownerFirstName", ownerFirstName+"%");
query.setParameter("ownerLastName", ownerLastName+"%");
query.setParameter("petType", "pet");
query.setParameter("petLastName", petLastName+"%");
query.setParameter("petFirstName", petFirstName+"%");
query.setFirstResult(nPageSize*nPageCount).setMaxResults(nPageSize);
return query.list();
Now the query returns the results as expected however, I want to know how many total records are in the result for paging purposes and I don't want to access that via
Code:
query.list().size()
since there could be a substantial number of records and the memory/performance hit would be way too costly.
I've tried using
Code:
int count = ((Integer)query.iterate().next()).intValue();
which returned a
java.lang.ClassCastException, and
Code:
int count = ((Integer)session.createFilter(query, "select count(*)").iterate().next()).intValue())
which returned
Hibernate ExceptionThe collection was unreferenced
java.lang.NullPointerException
What am I missing?