HQL: group by month

I am trying to group several months by month using HQL, but I am a little new to this API and cannot make it work.

Here is my code:

        Criteria query = getHibernateSession().createCriteria(SalesPerformance.class);

        // summary report is grouped by date
        query.setProjection(Projections.projectionList().add(
                Projections.groupProperty("effectiveDate"), "effectiveDate").add(
                Projections.groupProperty("primaryKey.seller", "seller").add(
                Projections.sum("totalSales"))));


        // sub-select based on seller id
        query.add(Property.forName("primaryKey.seller.id").eq(sellerId)).setFetchMode(
                "primaryKey.seller", FetchMode.SELECT);

        query.add(Property.forName("primaryKey.effectiveDate").le(new Date()));
        query.add(Property.forName("primaryKey.effectiveDate").ge(DateUtils.truncate(new Date(), Calendar.MONTH)));
        query.addOrder(Order.desc("primaryKey.effectiveDate"));

        return query.list();

My problem with this query is that it will return one row per day when I need one row per month due to Projections.groupProperty ("effectiveDate").

I thought about using Projections.sqlGroupProjection instead of Projections.groupProperty and threw it into some HQL, but the documentation and steam examples I found didn’t really help me understand how I would like to put the correct postresql statement in this method.

Anyone who knows about Postgres and HQL can give some hints here, please?

+3
1

:

Criteria query = getHibernateSession().createCriteria(SalesPerformance.class);

    // summary report is grouped by date
            query.setProjection(Projections.projectionList().add(Projections.sqlGroupProjection("date_trunc('month', eff_dt) as eff_dt_value", "eff_dt_value", new String[] {"eff_dt_value"}, new Type[] {Hibernate.DATE})).add(
                            Projections.groupProperty("primaryKey.seller", "seller").add(
                            Projections.sum("totalSales"))));


            // sub-select based on seller id
            query.add(Property.forName("primaryKey.seller.id").eq(sellerId)).setFetchMode(
                            "primaryKey.seller", FetchMode.SELECT);

            query.add(Property.forName("primaryKey.effectiveDate").le(new Date()));
            Date beginningOfLastMonth = DateUtils.truncate(DateUtils.addMonths(new Date(), -1) , Calendar.MONTH);
            Date endOfLastMonth = DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.MONTH), -1);
            query.add(Property.forName("primaryKey.effectiveDate").between(beginningOfLastMonth, endOfLastMonth));


            return query.list();

, effectiveDate .

, !:)

+6

Source: https://habr.com/ru/post/1709401/


All Articles