在hibernate中结合使用quarter函数

时间:2018-05-16 09:44:39

标签: java hibernate

我的查询如下,

SELECT 
    SUM(field1 * field2) AS summation,
    MONTH(date_field) AS months
FROM
    some_table
    where QUARTER(date_field) = QUARTER(CURDATE())
GROUP BY MONTH(date_field)

我想在hibernate中编写以上内容,但是我无法弄清楚如何在hibernate中编写季度功能。到目前为止,我有以下休眠标准,没有季度功能,如下所示,

ProjectionList proj = Projections.projectionList();

proj.add(Projections.sqlProjection("sum(field1 * field2) AS summation", new String[] { "summation" }, new Type[] {StandardBasicTypes.BIG_INTEGER }));

proj.add(Projections.sqlGroupProjection("month(date_field)  as months",  new String[] { "months" }, new Type[] { StandardBasicTypes.INTEGER }));

Criteria cr = getSession().createCriteria(some_table.class).setProjection(proj).add(conjunction);

我被困在如何写连词。谢谢。

1 个答案:

答案 0 :(得分:0)

基本上查询说的是date_field属于当前季度,所以我得到的解决方法是这样的,

conjunction.add(Restrictions.between("date_field",getFirstDayOfCurrentQuarter(),getLastDayOfCurrentQuarter() ));

其中两个函数getFirstDayOfCurrentQuarter()和getLastDayOfCurrentQuarter()给出当前季度的第一个和最后一个日期。这些功能如下,

private static Date getFirstDayOfCurrentQuarter() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)/3 * 3);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    }

    private static Date getLastDayOfCurrentQuarter() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)/3 * 3 + 2);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }