在我的数据库中,日期为 2012-04-09 04:02:53
2012-04-09 04:04:51
2012-04 -08 04:04:51
等,我需要在日期字段中检索当前日期的数据。我的意思是我只需要匹配 2012-04-09'
。我如何使用 hibernate 条件来做到这一点。
最佳答案
使用 Restrictions.between()生成日期列在 '2012-04-09 00:00:00' 和 '2012-04-09 23:59:59' 之间的 where 子句
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse("2012-04-09 00:00:00");
Date toDate = df.parse("2012-04-09 23:59:59");
criteria.add(Restrictions.between("dateField", fromDate, toDate));
请注意,Criteria API 中使用的所有属性都是 Java 属性名,而不是实际的列名。
更新:仅使用 JDK 获取当前日期的 fromDate 和 toDate
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date fromDate = calendar.getTime();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date toDate = calendar.getTime();
criteria.add(Restrictions.between("dateField", fromDate, toDate));
关于java - 如何在 hibernate 中比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073893/