Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

java - Group by month with criteria in Hibernate

I'm trying to get a report using Criteria and ProjectionList, and I'm pretty new using this through hibernate. So I have this model:

private Long _userId;

 private Category _category;

 private Long _companyId;

 private Double _amount;

 private Date _date;

And I building the query using this:

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

 }

Basically this method receive a Category and a userId to filter the payments records and a period, who will indicate how many months from now to back I want to sum. How can I get the sum result grouped by months?

Any help or tip I'll appreciate it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the answer, and its pretty simple. I changed the "groupProperty" in the ProjectionList criteria for this:

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

Okay. I'll explain the sqlGroupProjection. The first argument is the part of the query after of the "select", for example:

Select [firstPartOfSqlGroupProjection] * boo;

The "{alias}" is the alias that hibernates use in the query to refer to a table.

The second argument of the sqlGroupProjection function is the group by criteria, the third argument is the column names that you'll get from the group by and finally, the type of data you'll use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...