开发者

how to get Reusable Hibernate Criteria.?

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开发者_JAVA技巧.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..


This has been achieved by resetting 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.


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")));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜