【问题标题】:Hibernate date operations休眠日期操作
【发布时间】:2012-08-31 16:03:50
【问题描述】:

我在 DB2 中使用休眠并遇到以下问题。表/实体Customer 具有字段first_namelast_namebirthday(java.util.Date)。我需要编写一个查询来检索所有在接下来的四天内过生日的客户。问题是某些客户的出生年份是未知的,因此在数据库中将其设置为 9999,因此我不能只在 where 子句中进行简单的检查(因为是 9999 年)。

【问题讨论】:

  • 9999 如何转换为日期?
  • 对于未知值,通常最好使用 NULL,而不是虚拟变量。另外,您是否使用 HQL 或 Criteria API 查询数据库?
  • @Vikdor:有两种情况。首先是完整日期是已知的,因此保存到数据库中。其他情况是只知道出生日期和月份。例如,客户出生于 10.12,因此它将作为 10.12.9999 保存到数据库中,并且我不允许更改此逻辑。
  • @vstoyanov 我想使用 HQL,但也可以使用 Criteria API。
  • @alicica87 我已修改查询以符合 DB2 SQL 语法。

标签: java database hibernate db2 hql


【解决方案1】:

使用简单的 hql 查询

from Customer as user where month(user.birthday) = month(current_date()+4 days) and day(user.birthday) = day(current_date()+4 days)
union all
from Customer as user where month(user.birthday) = month(current_date()+3 days) and day(user.birthday) = day(current_date()+3 days)
union all
from Customer as user where month(user.birthday) = month(current_date()+2 days) and day(user.birthday) = day(current_date()+2 days)
union all
from Customer as user where month(user.birthday) = month(current_date()+1 day) and day(user.birthday) = day(current_date()+1 day)

【讨论】:

  • 我想这是我一直在寻找的,但是如果当前月份是 12 月,月份(current_date()+4) 的结果会是什么?
  • 取决于日期,如果日期是 28.12.2012 然后是 1。
  • 我不确定DB2 sql语法可能需要添加+4 days+1 day
  • 好的,我明白了。因此,您添加到 current_date 的数字就是天数。感谢您的帮助,您是否有关于此日期算术的一些参考资料的链接。
猜你喜欢
  • 2010-11-05
  • 1970-01-01
  • 2014-07-23
  • 2011-04-08
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
相关资源
最近更新 更多