tags:

views:

49

answers:

2

Hi,

How to clone criteria object?

I have created Criteria object for joining multiple tables and applying multiple restrictions. Then i need total number of records based on the restrictions applied.Then i need to apply pagination details(by set maxList) and have to retrive List of Objects.

    Criteria criteria = session.createCriteria(Property.class, "property")
                    .createAlias("property.propertyType", "type").createAlias(
                            "property.propertyConcern", "propertyConcern",
                            CriteriaSpecification.LEFT_JOIN).createAlias(
                            "propertyConcern.concern", "concern",
                            CriteriaSpecification.LEFT_JOIN).setResultTransformer(
                            CriteriaSpecification.DISTINCT_ROOT_ENTITY);


criteria = addMultipleSeachCriteria(criteria, condition);
    criteria.setFirstResult(
                        pageCriteria.getFirstRecordOfCurrentPage())
                        .setMaxResults(pageCriteria.getRecordsPerPage());

criteria.addOrder(pageCriteria.isSortDescending() ? Order
                            .desc(pageCriteria.getSortBy()) : Order
                            .asc(pageCriteria.getSortBy()));

When i run this i getting results as i expected. But i need to fetch number of records for the applied restrictions without applying order by and setmaxResults.?How do i achieve?I am not able clone the criteria object also..

A: 

The following is how i do it in NHibernate

DetachedCriteria newCriteria = CriteriaTransformer.TransformToRowCount(criteria);

Further more if you want to add some other information like SUM's you can add those with projections like thus:

newCriteria.SetProjection(Projections.ProjectionList()
                                         .Add(Projections.RowCount(), "rows")
                                         .Add(Projections.Sum("TaxAmount.Decimal"))
                                         .Add(Projections.Sum("NetAmount.Decimal"))
                                         .Add(Projections.Sum("GrossAmount.Decimal")));
F.B. ten Kate
Hi, Thanks for your response.Which Version of Hibernate is it? i am not able to get CriteriaTransformer class in my code.it shows error.Please help.
Jothi
i Want solution in hibernate. it seems, you posted for nHibernate
Jothi
Sorry, since it's a port i'd expect the same to exists for Hibernate but it seems it does not.
F.B. ten Kate
A: 

This has been achived by reseting projection result,

pageCriteria.setTotalRecords(((Integer) criteria
                            .setProjection(Projections.rowCount())
                            .uniqueResult()).intValue());
//Reset
criteria.SetProjection(null);
criteria.SetResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

But i am not sure whether it failures in any other scenario.

Jothi