2010-01-14 41 views
28

我試圖使用Criteria和ProjectionList得到一個報告,而且我很新,通過hibernate使用它。 所以我有這個模型:在Hibernate中按標準分組

private Long _userId; 

private Category _category; 

private Long _companyId; 

private Double _amount; 

private Date _date; 

而且我用這個構建查詢:

public List sumPaymentsByUserCategoryPeriod(Category category, Long userId,Integer period){ 
    GregorianCalendar from = new GregorianCalendar(); 
    from.add(Calendar.MONTH, -period); 
    List<CategoryAmount> resultDTO= new ArrayList<CategoryAmount>(); 

    Criteria criteria = getSession().createCriteria(Payment.class); 
    criteria.add(Restrictions.eq("_category", category)); 
    criteria.add(Restrictions.eq("_userId",userId)); 
    criteria.add(Restrictions.between("_date", from.getTime(), new Date())); 

    ProjectionList projectionList = Projections.projectionList(); 
    projectionList.add(Projections.sum("_amount")); 
    projectionList.add(Projections.groupProperty("_date")); 
    criteria.setProjection(projectionList); 
    return criteria.list(); 

} 

基本上這個方法接收類別和用戶ID來過濾付款記錄和一段時間,誰指示我想從現在到後退幾個月。我怎樣才能得到按月分組的總和結果?

任何幫助或提示我會感激它!

回答

37

我找到了答案,它非常簡單。我更改了ProjectionList標準中的「groupProperty」:

projectionList.add(Projections.sqlGroupProjection(
    "month({alias}.DATE) as month, year({alias}.DATE) as year", 
    "month({alias}.DATE), year({alias}.DATE)", 
    new String[]{"month","year"}, 
    new Type[] {Hibernate.DOUBLE})); 

好的。我將解釋sqlGroupProjection。第一個參數是所述查詢的所述部分的後「選擇」,例如:

Select [firstPartOfSqlGroupProjection] * boo; 

在「{}別名」是休眠在查詢使用,以指代表的別名。

sqlGroupProjection函數的第二個參數是按標準分組,第三個參數是您將從組獲得的列名稱,最後是您將使用的數據類型。

+3

如何處理不同的數據庫?如MSSQL和Oracle? 由於Oracle使用to_char和mssql使用weeknum ... – zolibra 2015-05-06 06:01:43

0

可以在休眠使用的SQLQuery,這裏有一個例子:

public List<MonthlyPoint> groupByMonth(ChartRequest request){ 

    SQLQuery query = getSession().createSQLQuery("SELECT \n" + 
     "sum(this_.amount) as amount, \n" + 
     "extract(month from this_.fecha) as month, \n" + 
     "extract(year from this_.fecha) as year\n" + 
     "FROM jornada this_ \n" + 
     "GROUP BY \n" + 
     "month, \n" + 
     "year \n" + 
     "ORDER BY \n" + 
     "year asc, \n" + 
     "month asc"); 

     query.setResultTransformer(Transformers.aliasToBean(MonthlyPoint.class)); 
     return query.list(); 
} 


public class MonthlyPoint { 
    private Double year; 
    private Double month; 
    private Double amount; 
    //-- getters and setters here -- 
}