无法在Hibernate Criteria中的两个日期之间获取数据

时间:2017-03-11 16:03:12

标签: java mysql hibernate hibernate-criteria

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

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 - 

我做错了什么?

1 个答案:

答案 0 :(得分:2)

使用以下

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

而不是

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

UPDATE:

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

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