【问题标题】:Hibernate Criteria - Date Comparison is Not Returning Correct Results休眠标准 - 日期比较未返回正确结果
【发布时间】:2015-11-02 15:12:40
【问题描述】:

我正在尝试检索在用户输入提供的日期范围内发生的一组记录。出于某种原因,即使有应该匹配的记录,条件也没有返回任何结果。

模型属性和样本数据:

@Column(name="date")
private Date date;

mysql> select * from student_interaction where id = X \G
*************************** 1. row ***************************
                 id: 23828
                 date: 2015-08-07 00:00:00
                 student_id: 2725
                 ... other columns ommitted
1 row in set (0.01 sec)

标准实现:

List<StudentInteraction> returnList = new ArrayList<StudentInteraction>();
    Criteria criteria = session.createCriteria(StudentInteraction.class);
    if(userID > 0) {
        List<Number> criteriaInList = new ArrayList<Number>();
        criteriaInList = session.createSQLQuery("select student_id from advisor_student where advisor_id = :userID").setInteger("userID", userID).list();
        if(criteriaInList != null && criteriaInList.size() > 0) {
            criteria.add(Restrictions.in("student.id", criteriaInList));
        }
    }
    criteria.add(Restrictions.ge("date", startDate));
    criteria.add(Restrictions.lt("date", endDate));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    returnList = criteria.list();
    return returnList;

参数值:

  • 开始日期:8 月 15 日星期三 00:00:00 PST 14(日期)
  • 结束日期:8 月 15 日星期四 00:00:00 PST 15(日期)
  • criteriaInList: (1521, 1840, 1852, 1914, 5431, 10748, 29017, 8056, 2725, 5505)

如您所见,记录的日期在提供的 startDateendDate 范围内,并且记录的 student_id 值包含在 criteriaInList 中放。有谁知道为什么 returnList 出来是 [] (空)?

【问题讨论】:

  • 您介意先检查硬编码的id 吗?在您的criteria.add(Restrictions.in("student.id", criteriaInList)) 中将criteriaInList 替换为new String[] { "2725" },看看会发生什么
  • 首先,感谢您的评论。但是,我使用硬编码列表得到了相同的结果。该问题似乎与 criteriaInList 限制无关,因为即使它从未进入 (userID > 0) 条件,结果仍然为空。

标签: java mysql hibernate date orm


【解决方案1】:

您是否尝试过直接在数据库上运行带有参数值的生成 sql? 这些开始/结束日期 GE 和 LT 值是否满足查询?

您可能只想从删除条件和开始/结束日期条件开始,然后一次添加一对一的条件。

【讨论】:

  • 根据您的建议,我只添加了criteria.add(Restrictions.ge("date", startDate)); 限制。无论 date 属性是否为 GE 而不是 startDate 参数,它都会返回所有 StudentInteraction 记录。任何想法为什么会这样?
  • 根据条件生成的 sql 怎么样?这是否也带来了所有记录?
猜你喜欢
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 2014-12-12
  • 2012-10-30
  • 2011-09-10
  • 1970-01-01
相关资源
最近更新 更多