我令人惊讶地无法获取两个日期之间的字段总和
我的方法是:

public static double getTotalfeeIncome(Date fromDate, Date toDate) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        double total = 0.0;
        try {
            tx = session.beginTransaction();
            Criteria cr = session.createCriteria(StudentFees.class);
            cr.add(Restrictions.eq("delFlg", "N"));
            cr.add(Restrictions.between("paymentDate", fromDate, toDate));
            log.debug(fromDate);
            log.debug(toDate);
            total = (Double) cr.setProjection(Projections.sum("paymentAmt")).uniqueResult();
            tx.commit();
        } catch (Exception asd) {
            log.debug(asd.getMessage());
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return total;
    }


当我尝试获得价值时:

double feeIncome = Expense.getTotalfeeIncome(fdate, tdate);


返回0,但是两个日期之间有数据。在我的catch部分中似乎没有打印出一个错误。我的记录器输出是:

[edulogger] [11 Mar 2017 - 18:54:48] [DEBUG][dao.Expense][getTotalfeeIncome] - Sat Mar 11 00:00:00 EAT 2017
2017-03-11 18:54:48,334 DEBUG com.orig.edu.dao.Expense edulogger:182 - Sat Mar 11 00:00:00 EAT 2017
[edulogger] [11 Mar 2017 - 18:54:48] [DEBUG][dao.Expense][getTotalfeeIncome] - Sat Mar 11 00:00:00 EAT 2017
2017-03-11 18:54:48,338 DEBUG com.orig.edu.dao.Expense edulogger:183 - Sat Mar 11 00:00:00 EAT 2017
Hibernate: select sum(this_.payment_amt) as y0_ from edutek.student_fees this_ where this_.del_flg=? and this_.payment_date between ? and ?
[edulogger] [11 Mar 2017 - 18:54:48] [DEBUG][dao.Expense][getTotalfeeIncome] -
2017-03-11 18:54:48,455 DEBUG com.orig.edu.dao.Expense edulogger:187 -


我做错了什么事?

最佳答案

使用以下

cr.add(criteria.add(Restrictions.ge("paymentDate", fromDate)));
cr.add(criteria.add(Restrictions.lt("paymentDate", toDate)));


代替

cr.add(Restrictions.between("paymentDate", fromDate, toDate));


更新:

cr.add(Restrictions.between("DATE(paymentDate)", fromDate, toDate));


资源链接:
https://stackoverflow.com/a/6122906/2293534

10-04 17:05