Question

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
Was it helpful?

Solution

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

OTHER TIPS

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


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top