2015-09-10 52 views
0

對於我在我的Web應用程序中使用的網格組件,我有一個通過Criteria的「GridModel」類。已經設置投影的條件上的休眠行計數

GridModel類有一種方法,可以通過將setFirstResult(...)setMaxResults(...)添加到標準中來獲取特定頁面的結果。

但我也需要行爲準則的總數,所以我有以下方法:

public int getAvailableRows() { 

    Criteria c = criteriaProvider.getCriteria(); 
    c.setProjection(Projections.rowCount()); 

    return((Long)c.uniqueResult()).intValue(); 
} 

這完美地工作,但現在我有一個要求,已經在使用setProjection()一個標準的網格與setResultTransformer()結合。看來getAvailableRows()以上方法overrides原始標準的setProjection()創建錯誤的結果。

我可以以某種方式包裝原始標準的計數標準嗎?或者我會如何解決這個問題?

回答

0

我嘗試使用Projections.rowCount()groupBy表達式結合使用時遇到過類似的問題。我能夠規避在一個稍微「哈克」的方式事情:

  1. 記住以前的投影和結果變壓器
  2. 在基準設定投影是一個修改版本(見下文)
  3. 執行行計數DB命中
  4. 恢復以前的投影+變壓器這樣的標準,可用於實際結果檢索如果

    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(); 
    

幾個注意事項這裏:

  1. 這仍然不會得到預期的結果,如果你試圖用一個sum投影給它一個標準爲不被視爲一個isGrouped()投影 - 它將圖示與總和一個計數。我不認爲這是一個問題,因爲獲得該性質的表達式的rowcount可能沒有意義
  2. 當我在處理這個問題時,我寫了一些單元測試以確保rowcount的預期沒有預測,基於屬性的預測並與groupby預測,但我寫這從記憶中,所以不能保證小扭結將不需要熨燙出