hibernate:将复杂的hql转换为条件

时间:2014-01-03 09:02:47

标签: java sql-server hibernate hql criteria

我有一个任务实体,有一个网站

实体

public class Task {
    // ....

    @Column(name = "START_DATE")
    @Temporal(value = TemporalType.TIMESTAMP)
    public Date getStartDate() {
        return startDate;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SITE_NO")
    public Site getSite() {
        return site;
    }

}

HQL

select id from Task main
where exists (
    select site.id, MAX(startDate) as latest_date from Task sub
    group by site.id
    having main.startDate = MAX(startDate)
)

上面的hql工作正常。结果集是GROUP BY site和MAX(startDate)的所有任务 但是标准是首选的。
我尝试了以下代码,但无法将having子句转换为条件。

标准

DetachedCriteria detachedCriteria = service.createDetachedCriteria();
detachedCriteria.setProjection(Projections.projectionList()
        .add(Projections.groupProperty("site.no"))
        .add(Projections.max("startDate"))
        // [having clause]
    );

Criteria criteria = service.createCriteria();
criteria.add(Subqueries.exists(detachedCriteria));

1 个答案:

答案 0 :(得分:1)

我们可以通过添加子查询来添加功能。我将max(startdate)作为内部查询添加到变通方法中。

DetachedCriteria detachedCriteria = service.createDetachedCriteria();
detachedCriteria.setProjection(Projections.projectionList()
    .add(Projections.groupProperty("site.no"))
    .add(Projections.max("startDate"))
    // [having clause]
    );

Criteria criteria = service.createCriteria();
criteria.add(Subqueries.exists(detachedCriteria));
criteria.add(Subqueries.eq("startDate", innerQuery));