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开发者_如何学C , 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 ?)
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
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.
精彩评论