简体   繁体   中英

Hibernate detached queries as a part of the criteria query

java experts can you please help me write detached queries as a part of the criteria query for the following SQL statement.

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

You need to write a correlated subquery . Assuming property / class names match column / table names above:

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);

Just one addition to the above query. If the entryid is not the primary key, then you'll need to add projection.


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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM