2013-04-22 83 views
0

我有一个表中有两个时间戳列表示effectiveexpiration日期,我需要获取当前时间戳落在这两个日期列中的那些行。基于休眠中的某些条件的两个日期列中的日期

这可以通过在SQL查询中添加条件来完成,如下所示
effectiveDate <= current_timestamp and current_timestamp < expirationDate

问题是,如果expirationDate不为空,则应满足上述条件。如果它是空的,那么只有
effectiveDate <= current_timestamp将被检查。

这是一种动态SQL,我猜。我在项目中使用Hibernate。我可以使用critera API或HQL或SQL任何东西。

请让我知道如何做到这一点。

回答

1

你的第一个版本并不完全是SQL。但是你想要的是这样的:

where effectiveDate <= current_timestamp and 
     (expirationDate is NULL or current_timestamp < expirationDate) 
0

没有什么动态的你想要的SQL。试试这个:

Criteria c = sf.getCurrentSession().createCriteria(MyObject.class) 
    .add(Restrictions.lt("effectiveDate",dateArgument)) 
    .add(Restrictions.or(
     Restrictions.isNull("expirationDate"), 
     Restrictions.gt("expirationDate",dateArgument))); 

调用c.list()将返回每个MyObject具有比给定日期以下的effectiveDate也有一个expirationDate比给定的日期或者null或更大。

只要你不介意使用Hibernate Criteria Queries,就应该给你想要的东西。

注意:随意使用根据您的具体要求.le(...).ge(...)交换.lt(...).gt(...)