Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count(*) in hibernate criteria?

Tags:

I have a combination of search criteria which implemented by using hibernate criteria. And I added a pagination like this :

criteria.setFirstResult(offset).setMaxResults(pageSize).setFetchSize(pageSize).list(); 

This is not enough for a pagination , so I have count the total result size .

totalResult = (Integer)criteria.setProjection(Projections.rowCount()).uniqueResult(); 

The problem is , the first time I submit the search form , I got correct totalResult. When I click next page , and the offset changes , I got a NullPointExcetion at second statement . I don't know why . And through debugging , I can see when this exception occurs , the first statement successfully return the paginated results.

So I want to ask , does the first statement conflict the second ? (because the first statement set the fetchsize to 10 , and I wonder if the count(*) function will work properly. they are different task using same criteria , How can I clone or copy one criteria that already has numerous restrictions been added ?)

like image 989
Sawyer Avatar asked Jan 29 '10 06:01

Sawyer


2 Answers

Just to fix count(*) query - better use this code for criteria:

Integer totalResult = ((Number)criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue(); 

otherwise you will get an error java.lang.Long cannot be cast to java.lang.Integer

like image 72
Brahma Avatar answered Oct 18 '22 13:10

Brahma


I think the conflict is actually the restriction in the count query, so I'd expect it to return wrong results on the second run of the pagination query.

Using a single Criteria for both requires some resetting between uses, which can probably be done along the lines of:

 criteria.setProjection(null)          .setResultTransformer(Criteria.ROOT_ENTITY); 

If you really want two separate but identical criteria, I think the easiest way is to first create a DetachedCriteria, which is Serializable, and use the serialization-deserialization cloning hack to make another one, before converting them to normal Criteria by attaching to a session.

But if you can work in a reset, you might not need two.

like image 22
Don Roby Avatar answered Oct 18 '22 11:10

Don Roby