如何编写简单的Hibernate Criteria子查询

时间:2017-10-03 12:07:47

标签: java hibernate jpa criteria hibernate-criteria

如何在Java中将此SQL查询编写为Hibernate JPA Criteria(带限制等)?

SELECT q.* FROM queue AS q WHERE q.executed = false AND q.queued_on = (SELECT min(queued_on) FROM queue WHERE item_id = q.item_id);

我只设法编写第一部分:

getBaseCriteria()
    .add(Restrictions.eq("executed", false))
    // Missing Second Where Filter Here
    .addOrder(Order.asc("queuedOn"))
    .list();

1 个答案:

答案 0 :(得分:1)

尝试为子查询创建单独的条件实例,并简单地添加另一个限制,如下所示:

DetachedCriteria subCriteria = DetachedCriteria.forClass(Queue.class, "sub")
    .add(Restrictions.eqProperty("sub.itemId","main.itemId"))
    .setProjection(Projections.projectionList().add(Projections.min("sub.queuedOn")));

session.createCriteria(Queue.class, "main")
   .add(Subqueries.propertyEq("main.queuedOn", subCriteria ));
   .add(Restrictions.eq("main.executed", false));
   .addOrder(Order.asc("main.queuedOn"))
   .list();