Hi everyone!
I would like to set up a vote on the implementation of count()/rowCount() on the Criteria API. Lots of people in Hibernate community got frustrated with implementation (?) of that functionality in Hibernate 3.x and lack of it in "official" release of Hibernate 2.x. Patch for H2.x was very helpful, but it was not exactly what it needs to be. However, moving to Hibernate 3.x even that piece of functionality gets ugly in implementation. Example:
Criteria search = built by set of recursive calls of criteria builder function based on user request.
Before (with patch):
Code:
....
int count = (int) search.count();
....
// Calculate firstResult, maxResults based on page size and count
....
search = search.setFirstResult(firstResult).setMaxResults(maxResults);
Collection result = search.list();
....
Now:
Code:
.....
search.setProjection(Projections.rowCount());
count =((Integer) search.uniqueResult()).intValue();
search.setProjection(null);
....
// Calculate firstResult, maxResults based on page size and count
....
Collection result = search.list();
.....
and it does not work if you have orderBy set on your search criteria and there is no way to clear it and set it again in Criteria API. Also it will not give you size of result set if you are using aggregate functions and/or group by. Patch for H2.x did not provide that as well.
What people were asking for many years is to implement functionality that will allow us to determine a size of result set. And it has nothing to do with either Projection API or patterns or approaches that were used in H3.x design. It just doest not exists in Hibernate. This kind of functionality by nature belongs to Criteria API not to Projection. Projection provides ability to use grouping and aggregate functions execution. Count (not rowCount) is one of them and here is nothing wrong. However, there is nothing that give us information about result set size. It has to be rowCount (or resultSize or what ever you call it) on Criteria API. IT IS NOT AN AGGREGATE FUNCTION (but can be implemented through it) I am sorry, but tracking that issue since 2003 nobody was listening what people complains about, what actual needs in real development world. Simple functionality that is used in 80% of all implementations still a challenge to implement. I think it comes from misunderstanding a difference. May be this example in SQL will give a difference filling between aggregate count() and rowCount() of result (MS SQL dialect):
Code:
select account_id, count(*) from transaction group by account_id
select @@ROWCOUNT
P.S. It is only example not a suggestion. It can be implemented as a dialect neutral by using count and subqueries.
I am asking Hibernate community to vote for that or just say what your thoughts are.
Thank you for your patience to read all this.