【问题标题】:Restrictions Between for Date in Hibernate Criteria休眠条件中日期的限制
【发布时间】:2011-05-25 10:14:16
【问题描述】:

您好,我在我的示例中使用休眠。对于 bean 表审计试用,我想获取包含上限和下限的日期范围之间的审计试用。 我的代码如下所示

Criteria criteria = session.createCriteria(AuditTrail.class);

criteria.add(Restrictions.between("auditDate", sDate, eDate));

我的开始日期是25/11/2010。和结束日期是25/05/2011。但它只给出结果到@ 987654324@。它不执行包容性搜索。任何其他方式来做到这一点。 我正在使用 SQL 服务器。

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    我假设您的 auditDate 实际上是一个时间戳。如果是这种情况,那么这是正常的,因为 25/05/2011 表示 25/05/2011 的 0 点(早上)。因此,当然,在 2011 年 5 月 25 日具有审计时间戳的每一行都在早上 0 点之后。

    我会在您的结束日期上增加 1 天,并使用 auditDate >= sDate and auditDate < eDate

    criteria.add(Restrictions.ge("auditDate", sDate)); 
    criteria.add(Restrictions.lt("auditDate", eDate));
    

    【讨论】:

    • Protip:如果你不需要像上面的OP那样处理时间组件,你可以使用le(..)(而不是lt(..) + messy date算术)。
    【解决方案2】:

    criteria.add(Restrictions.between("DATE(auditDate)", sDate, eDate)); 使用它来忽略从日期开始的时间。

    【讨论】:

    • 这给出了错误:“无法解析属性:DATE(auditDate)”
    【解决方案3】:
     criteria.add(Restrictions.ge("fromDate", DateUtil.persianToGregorian(currentDate)));
     criteria.add(Restrictions.le("toDate",  DateUtil.persianToGregorian(currentDate)));
    
     return criteria.list();
    

    【讨论】:

      【解决方案4】:

      结束日期再增加一天

       @Autowired
       private SessionFactory sessionFactory;
      
       String startDate = "2019-07-31 ";
       String endDate = "2019-08-24 ";
      
       Date fromDate = format.parse(fromDate);
      
       /* Add one more day to the end date*/
      
       Date to =format.parse(endDate);
       Calendar today = Calendar.getInstance();
       today.setTime(dateto);
       today.add(Calendar.DAY_OF_YEAR, 1);
      
       Date toDate= format.parse(format.format(today.getTime()));
      
       Criteria crit = sessionFactory.getCurrentSession().createCriteria(model.class);
       crit.add(Restrictions.between("dateFieldName", fromDate, toDate));
       List result = crit.list();
      

      【讨论】:

        猜你喜欢
        • 2011-07-14
        • 2011-08-13
        • 1970-01-01
        • 2011-09-10
        • 2011-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-27
        相关资源
        最近更新 更多