Search code examples
javamysqlhibernatehibernate-criteria

Unable to fetch data between two dates in Hibernate Criteria


I am surprisingly unable to fetch the sum of a field between two Dates My method is:

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

When I try to get the value:

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

returns 0 but there is data between the two dates. There seem to be an error that is not getting printed out in my catch section. My logger output is:

[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 - 

What is it that I am doing wrong?


Solution

  • Use the following

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

    instead of

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

    UPDATE:

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

    Resource Link: https://stackoverflow.com/a/6122906/2293534