[英]Hibernate Criteria how to sort a row count projection on a parent child relationship
[英]Hibernate row count on Criteria with already set Projection
對於Web應用程序中的網格組件,我有一個“ GridModel”類,該類通過了Criteria。
GridModel類具有一種方法,該方法通過將setFirstResult(...)
和setMaxResults(...)
到Criteria來獲取特定頁面的結果。
但是我還需要條件的總行數,因此我有以下方法:
public int getAvailableRows() {
Criteria c = criteriaProvider.getCriteria();
c.setProjection(Projections.rowCount());
return((Long)c.uniqueResult()).intValue();
}
這完美地工作了,但是現在我有了一個網格,該網格要求已經使用setProjection()
和setResultTransformer()
的Criteria。 似乎上面的getAvailableRows()
方法overrides
原始Criteria的setProjection()
,從而產生錯誤的結果。
我可以以某種方式將計數標准包裹在原始標准周圍嗎? 或我該如何解決?
嘗試將Projections.rowCount()
與groupBy
表達式結合使用時,我也有類似的經歷。 通過以下方式,我能夠以一種“變態”的方式規避事物:
恢復以前的投影+轉換器,以便在以下情況下可以將“標准”用於實際結果檢索:
final Projection originalProjection = criteriaImpl.getProjection(); final ResultTransformer originalResultTransformer = criteriaImpl.getResultTransformer(); final Projection rowCountProjection; // If we identify that we have a function with a group by clause // we need to handle it in a special fashion if ( originalProjection != null && originalProjection.isGrouped() ) { final CriteriaQueryTranslator criteriaQueryTranslator = new CriteriaQueryTranslator( (SessionFactoryImplementor)mySessionFactory, criteriaImpl, criteriaImpl.getEntityOrClassName(), CriteriaQueryTranslator.ROOT_SQL_ALIAS ); rowCountProjection = Projections.projectionList() .add( Projections.rowCount() ) .add( Projections.sqlGroupProjection( // This looks stupid but is seemingly required to ensure we have a valid query "count(count(1))", criteriaQueryTranslator.getGroupBy(), new String[]{}, new Type[]{} ) ); } else { rowCountProjection = Projections.rowCount(); } // Get total count of elements by setting a count projection final Long rowCount = (Long)criteria.setProjection( rowCountProjection ).uniqueResult();
這里有一些警告:
sum
投影的條件,這仍然不會給出預期的結果,因為這不被視為isGrouped()
投影-它將使總和帶有計數。 我不認為這是個問題,因為獲取這種性質的表達式的行數可能沒有任何意義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.