使用 Hibernate HQL 选择两个日期在指定间隔内的记录

发布于 2024-07-28 22:44:02 字数 274 浏览 2 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒与心事 2024-08-04 22:44:02

必须是日历月吗? 在这种情况下,恐怕没有好的仅 HQL 解决方案。 你能得到的最接近的东西是:

from com.ep.cqprojects.db.Projects
 where active_date - kickoff_meeting_date < 31
   and month(active_date) - month(kickoff_meeting_date) < 2

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:

from com.ep.cqprojects.db.Projects
 where active_date - kickoff_meeting_date < 31
   and month(active_date) - month(kickoff_meeting_date) < 2

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 where active_date is last day of previous month and kickoff_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.

七七 2024-08-04 22:44:02

唉,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文