Hibernate分离查询作为条件查询的一部分

时间:2009-10-30 07:09:44

标签: java sql hibernate hql criteria

java专家可以帮助我编写分离查询作为以下SQL语句的条件查询的一部分。

select A.*
FROM AETABLE A
where not exists
(
    select entryid
    FROM AETABLE B
    where B.classpk = A.classpk
    and B.userid = A.userid
    and B.modifiedDate > A.modifiedDate
)
and userid = 10146

2 个答案:

答案 0 :(得分:14)

你需要写一个correlated subquery。假设属性/类名与上面的列/表名匹配:

DetachedCriteria subquery = DetachedCriteria.forClass(AETable.class, "b")
 .add(Property.forName("b.classpk").eqProperty("a.classpk"))
 .add(Property.forName("b.userid").eqProperty("a.userid"))
 .add(Property.forName("b.modifiedDate").gtProperty("a.modifiedDate"));

Criteria criteria = session.createCriteria(AETable.class, "a")
 .add(Property.forName("userid").eq(new Integer(10146)))
 .add(Subqueries.notExists(subquery);

答案 1 :(得分:6)

上述查询只是一个补充。如果entryid不是主键,那么您需要添加投影。


DetachedCriteria subquery = DetachedCriteria.forClass(AETable.class, "b")
 .add(Property.forName("b.classpk").eqProperty("a.classpk"))
 .add(Property.forName("b.userid").eqProperty("a.userid"))
 .add(Property.forName("b.modifiedDate").gtProperty("a.modifiedDate"))
 .add(setProjection(Projections.property("entryId"));  // Additional projection property

Criteria criteria = session.createCriteria(AETable.class, "a")
 .add(Property.forName("userid").eq(new Integer(10146)))
 .add(Subqueries.notExists(subquery);