找到下一个空闲时段

时间:2012-08-09 08:03:45

标签: sql hibernate hql

我有一个db表(Hibernate conf全部完成),

  ResourceRequest( resource, startTime, endTime, status )
在startTime和endTime之间

资源被占用。

问题陈述: 对于 inStartTime inEndTime 的输入,如果已经在给定的插槽中占用,我必须找到下一个可用的插槽。 必须为此编写一个hibernate查询。

我能想到的一个快速解决方案是: 将给定资源的资源请求查询到集合中,然后对其进行操作以获取下一个可用插槽。

但我想把它作为我的最后手段。任何帮助表示赞赏。

感谢。

1 个答案:

答案 0 :(得分:2)

在sql中

SELECT * FROM slots s1 WHERE
    s1.endTime > :inStartTime AND
    not exists (SELECT 1 FROM slots s2 WHERE s2.startTime > s1.endTime AND s2.startTime < DateAdd(s1.endTime, :inEndMinusInStart))
ORDER BY
    s1.startTime


// and criteria to tweak

DetachedCriteria subquery = DetachedCriteria.for(Slot.class)
    .add(<filter on resource>)
    .add(Restrictions.propertyGt("startTime", "s1.endTime"));
    .add(Restrictions.propertylt("startTime", Projections.sqlFunction("dateadd", Projections.property("s1.endTime"), inStartTime - inEndTime, Hibernate.dateTime));

session.createCriteria(Slot.class, "s1")
    .add(<filter on resource>)
    .add(Restrictions.gt(endTime, inStartTime))
    .add(Subqueries.notExists(subquery))

希望有所帮助

相关问题