查找日期在起始日期和结束日期之间的Hibernate实体,可以为null

时间:2011-03-12 21:13:25

标签: mysql hibernate jpa

我想找到在特定日期有效的所有活动实体。例如:

from Event where startDate <= :specifiedDate and endDate > :specifiedDate

但是,Event.startDateEvent.endDate可以是nullnull值表示没有开始日期或结束日期(开始是无限期的,或者结尾是无限的)。

那么,if Event.startDate = null and Event.endDate = 2011-05-01,那么应该为所有指定的值小于2011-05-01返回该事件。

同样if Event.startDate = 2011-03-01 and Event.endDate = null,那么对于大于或等于2011-03-01的所有指定日期值,应该返回该事件。

最后,if Event.startDate = null and Event.endDate = null,然后应该为任何指定的日期返回事件。

这可能是使用Hibernate和MySQL后端吗?

1 个答案:

答案 0 :(得分:4)

这当然是可能的。

使用标准应该是:

List events = sess.createCriteria(Event.class)
                 .add( Restrictions.or(
                          Restrictions.isNull("startDate"),
                          Restrictions.ge("startDate", specifiedDate))
                 .add( Restrictions.or(
                          Restrictions.isNull("endDate"),
                          Restrictions.lt("endDate", specifiedDate))
               .list();