Tuesday, 29 May 2012

How do we count rows using criteria in hibernate ?

We can get the rows count using the Projections. 


My code is like this: 


Criteria criteria = session.createCriteria(getReferenceClass()); criteria.setProjection(Projections.rowCount()); return ((Integer)criteria.list().get(0)).intValue();

-----------------------------------------------------------------------------------------------------------------------------------

Another solution is the following: 
1. run your criteria.list() without setting any alias => the referenced sets/list of the root entity will be filled with proxies => here you set correctly the max results and such 
2. run the alias criteria on its own in the same hibernate session => the above proxies will be initialized

something like this:


Code:
    Criteria criteria = this.getSession().createCriteria(User.class);
    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    criteria.setMaxResults(10);

    // First get the results without joining with the other tables
    List<User> results = criteria.list();

    // at this point the set roles is filled with proxies
    // we'll now create and execute the join so these proxies are filled since we're still in the same session
    getSession().createCriteria(User.class, "u")
            .createAlias("u.roles", "r", CriteriaSpecification.LEFT_JOIN)
            .list();

    return results;

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...