日期大于的hibernate查询

时间:2013-03-28 16:23:19

标签: java hibernate spring-mvc

我一直试图找到一种方法来查询我的表格中所有日期超过7天的日期。

这是我在工作中遇到的事情,但它不起作用:

    @SuppressWarnings({ "unchecked", "rawtypes" })
public List<Ownership> findOwnersByDate() {
    log.debug("finding a filtered list of Ownerships");
    Session session = getSessionFactory().getCurrentSession();
    try {
        session.beginTransaction();
        Criteria crit = session.createCriteria(Ownership.class)
        .add( Restrictions.gt("modDate", new Integer(7) ) ); 
        List results = crit.list();
        log.debug("get filtered ownerships successful, 
                    result size: " +  results.size());
        return results;
    } catch (RuntimeException re) {
        log.debug("query failed", re);
        log.error("get filtered ownerships failed", re);
        throw re;
    }
}

1 个答案:

答案 0 :(得分:3)

尝试传递与当前日期相对应的Date对象减去7天,而不是将new Integer(7)传递给Restrictions.gt()。您可以使用Calendar类,例如:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
...
Criteria crit = session.createCriteria(Ownership.class)
    .add( Restrictions.gt("modDate", cal.getTime() ) );