How to get reusable sleeping criteria.?

How to clone an object criteria?

I created a Criteria object to join multiple tables and apply multiple constraints. Then I need the total number of records based on the restrictions applied. Then I need to apply the pagination data (using set maxList) and get a 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 get the results as I expected. But I need to get the number of records for the restrictions applied without applying order and setmaxResults. How can I achieve? I also cannot clone the criteria object.

+3
source share
2 answers

This was achieved by resetting the projection result,

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

But I'm not sure if these are failures in any other scenario.

+6

, NHibernate

DetachedCriteria newCriteria = CriteriaTransformer.TransformToRowCount(criteria);

, - , ​​ SUM, , , :

newCriteria.SetProjection(Projections.ProjectionList()
                                         .Add(Projections.RowCount(), "rows")
                                         .Add(Projections.Sum("TaxAmount.Decimal"))
                                         .Add(Projections.Sum("NetAmount.Decimal"))
                                         .Add(Projections.Sum("GrossAmount.Decimal")));
-1

Source: https://habr.com/ru/post/1763421/


All Articles