tags:

views:

410

answers:

1

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 ?)

+1  A: 

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.

Don Roby
Thanks , actually my solution is exactly the same with your answers. It works !
ZZcat