【问题标题】:Can HQL substract or sum date fields?HQL 可以减去或求和日期字段吗?
【发布时间】:2009-10-16 10:00:13
【问题描述】:

A 有两个实体。例如时间设置和订单。

@Entity
public class TimingSettings{

    @Basic
    private Long orderTimeout = 18000; //for example 18000 sec
    ....
}


@Entity
public class Order{

    @Basic
    @OneToOne
    private TimingSettings timingSettings;

    @Temporal(value = TemporalType.TIMESTAMP)
    @Column(nullable = false)
    protected Date time;
    ....
}

我无法选择之前的超时并计算所需的订单时间,因为我不知道哪些订单有哪些时间设置。

我可以执行以下相同的 HQL:

select o from order o 
left join o.timingSettings ts
where o.time < current_timestamp()+ ts.orderTimeout

【问题讨论】:

    标签: hibernate timestamp hql


    【解决方案1】:

    这取决于您是否需要它在所有数据库中工作。

    在后一种情况下(特定数据库),请检查您的方言以获取可用的日期功能。 例如,MySQL 方言支持 timediff()time_to_sec() 函数,这将允许您将查询编写为:

    select o from order o 
      left join o.timingSettings ts
     where time_to_sec(timediff(o.time, current_timestamp())) < ts.orderTimeout
    

    如果您需要对所有数据库执行此操作(或者如果您的数据库不支持所需的日期函数),Hibernate 支持所有方言的year(), month(), ... second() 函数。使用这些会使您的查询变得相当冗长 :-) 加上您会遇到 DST 问题。

    【讨论】:

      【解决方案2】:

      问题在于算术和时间戳,请查看thread 了解一些想法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        • 2017-08-12
        • 2013-02-05
        • 2017-04-25
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多