Hibernate Criteria API中两个属性之间的日期

时间:2017-10-04 07:55:00

标签: java sql hibernate oracle11g

我正在尝试使用Criteria API获取日期在My database中的两个字段之间的记录。我需要构建一个看起来像的查询:

select tran_date_bal from eod_acct_bal_table where acid = <MyAcid> and <BalanceDate> between eod_date and end_eod_date;

由于提供的between不允许两个属性,我对获取日期标准感到困惑。以下是我到目前为止的情况:

private static double getEndOfDayBalanceAsAtDate(String foracid, Date BalanceDate) {
        double balance = 0;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Criteria cr = session.createCriteria(EodAcctBalTable.class);
            cr.add(Restrictions.eq("acid", getAcid(foracid)));
            cr.add(Restrictions.between());//****Stuck Here***********
            balance = (Double) cr.setProjection(Projections.property("tranDateBal")).uniqueResult();
            tx.commit();
        } catch (Exception asd) {
            log.debug(asd.getMessage());
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
        return balance;
    }

如何在遵守Criteria的同时生成查询?

1 个答案:

答案 0 :(得分:3)

Restrictions.between只接受价值观,所以你不能在这里使用它,我很害怕。

您可以使用lege

构建等效查询
cr.add(Restrictions.le("eod_date", /** balance date **/));
cr.add(Restrictions.ge("eod_date_end", /** balance date **/));

另一种选择是使用sqlRestriction

cr.add(Restrictions.sqlRestriction("? between eod_date and eod_date_end", /** balance date **/, StandardBasicTypes.DATE ));