[英]Group by month with criteria in Hibernate
我正在尝试使用Criteria和ProjectionList获取报告,而我通过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();
}
基本上这种方法会收到一个Category和一个userId来过滤付款记录和一个期间,这个期间将指示从现在到我想要总和多少个月。 如何按月分组总和结果?
任何帮助或提示,我会很感激!
我找到了答案,而且非常简单。 我更改了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”之后的查询部分,例如:
Select [firstPartOfSqlGroupProjection] * boo;
“{alias}”是休眠在查询中用于引用表的别名。
sqlGroupProjection函数的第二个参数是按条件分组,第三个参数是您将从组中获取的列名,最后是您将使用的数据类型。
你可以在hibernate中使用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 --
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.