使用 Hibernate HQL 选择两个日期在指定间隔内的记录
我正在尝试使用 HQL 查找两个日期字段彼此相差不超过 1 个月的记录。
Query query = session.createQuery("from com.ep.cqprojects.db.Projects "
+ "where active_date - kickoff_meeting_date < interval '1' month ");
不幸的是,使用的数据库显然不理解间隔。
如何比较两个日期字段之间的间隔?
I'm trying to use HQL to find records where two date fields are within 1 month of each other.
Query query = session.createQuery("from com.ep.cqprojects.db.Projects "
+ "where active_date - kickoff_meeting_date < interval '1' month ");
Unfortunately the database used apparently doesn't understand interval.
How can I compare the interval between two date fields?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
必须是日历月吗? 在这种情况下,恐怕没有好的仅 HQL 解决方案。 你能得到的最接近的东西是:
month()
是 ANSI SQL 函数,因此希望你的数据库引擎应该支持(顺便问一下,那是什么数据库?)需要第二个条件来排除以下情况:active_date
是上个月的最后一天,kickoff_meeting_date
是下个月的第一天,两者之间的月份长度不超过 31 天。如果需要,您可以进一步延长此时间以处理时间。 然而,最终,您最好获得近似结果并在代码中进一步重新检查/过滤它们。
Does it have to be a calendar month? I'm afraid there's no good HQL-only solution in that case. The closest thing you can get is:
month()
is ANSI SQL functions and so hopefully should be supported by your database engine (incidentally, what database is that?) Second condition is needed to weed out cases whereactive_date
is last day of previous month andkickoff_meeting_date
is first day of next month with month in between them less than 31 days long.You can further extend this to handle time if you need to. Ultimately, however, you may be better off getting approximate results and further re-checking / filtering them in your code.
唉,JPQL 还没有完全实现。 要准确比较两个日期字段,需要一个查询将相关实体引入日期(DATE 或 TIMESTAMP)Java/JPA 对象类型,然后比较它们(建议使用 Java Calendar 或 JodaTime)日历类。 一旦到达那里,从其中一个日历中减去一个月,然后比较两者之间的差异(以天、小时等为单位)将得出准确的结果。 请参阅 Java Calendar.add() 和 Calendar.before() 或 after() 方法。
Alas, JPQL is not quite there yet. To compare two date fields accurately will require a query to bring the entities in question into date (DATE or TIMESTAMP) Java/JPA object types and then compare them (with the recommendation being to use the Java Calendar or JodaTime) calendar classes. Once there, subtracting one month from one of the calendars and then comparing the difference (in days, hours, etc) between the two will yield an accurate result. See Java Calendar.add() and Calendar.before() or after() methods.