我想使用hibernate HQL执行数据时间操作。

我想添加和减去两个日期以及我想从特定日期减去1年或1个月。

如何在hibernate中使用HQL实现这一点?

有帮助吗?

解决方案

请参阅 在HQL中执行日期/时间数学? 举个例子。

要使用自定义sql,您必须编写自己的hibernate方言并注册:

registerFunction("weekday", 
  new SQLFunctionTemplate(Hibernate.INTEGER, "to_char(?1,'D')") );

其他提示

你需要创建自己的方言。如下所示:

public class MyDialect extends MySQLInnoDBDialect{
      public myDialect() {
      super();
      registerFunction("date_add_interval", new SQLFunctionTemplate(Hibernate.DATE, "date_add(?1, INTERVAL ?2 ?3)"));
      }
    }

在Hibernate / MySQL中(至少) 您可以转换为Unix时间戳和从Unix时间戳转换。由于unix时间戳是一个整数,你可以为它添加一个整数秒。

FROM_UNIXTIME(UNIX_TIMESTAMP(date)+ (allowedTimeWindow*86400)) as deadline

它有局限性,但比上述方法容易得多。

这是Hibernate中的一个开放问题。从Hibernate 3.3开始,没有标准的方法来处理纯粹在HQL中的日期比较:

https://hibernate.atlassian.net/browse/HHH-2434

Hibernate 4.3提供了在HQL中访问日期/时间的功能:

current_timestamp() , current_date() , current_time()

算术运算可以通过以下方式管理:

SECOND(...) , MINUTE(...) , HOUR(...) , DAY(...) , MONTH(...) , YEAR(...)

免责声明:我是Java新手

我能够在Hibernate 3.5.3中针对Sybase数据库的HQL语句中使用current_date() >= fromDate AND dateadd(day, -1, getdate()) <= toDate,而无需注册任何函数。

JPA + Hibernate 4.3.1 + MySQL 5方言的方法用法示例

public class SampleMySQL5InnoDBDialect extends org.hibernate.dialect.MySQL5InnoDBDialect {

public SampleMySQL5InnoDBDialect() {
    super();
    registerFunction("date_sub_days", new SQLFunctionTemplate(StandardBasicTypes.DATE, "date_sub(?1, interval ?2 day)"));
}

然后为您的类添加映射注释:

@NamedQuery(name = "SampleEntity.getSampleEntitiesForGapOverlapCalculations", query = "from SampleEntity as se where "
    + "((se.toDate between :startDate and :endDate) or (date_sub_days(se.toDate, se.duration) between :startDate and :endDate)) order by se.toDate asc, se.duration desc")

SampleEntity 包含 toDate 字段,类型为java.sql.Date, 持续时间 整数字段(持续时间以天为单位),我们正在计算 fromDate = toDate - duration ,并选择所有 fromDate 的实体 [startDate,endDate] 中的strong>或 toDate

Hibernate4.3提供本机函数来访问日期/时间戳并对它们执行算术操作

此处是可以在HQL中使用哪些表达式的文档的链接。 其中很少我提到: 访问日期/时间:

current_date(), current_time(), and current_timestamp()

算术运算可以通过以下方式完成。这些函数将Time作为输入:

second(...), minute(...), hour(...), day(...), month(...), and year(...)

可以通过

获得HQL的绝对差异
current_timestamp() - dateInstance

其中dateInstance可以有定义

@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date updatedAt;

结果是0.1秒。因此,对于1秒的绝对差异,上面的表达式将得到10的结果。

所以查询看起来像:

select t from Table t where (current_timestamp() - updatedAt)>600

Postgres用户......

registerFunction("dateadd", new SQLFunctionTemplate(StandardBasicTypes.DATE, "(?1 + INTERVAL ?2)"));

使用SQL用法:

now() < dateadd(:mydate, '-1 day')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top