views:

646

answers:

2

Hi Hibernate, 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
+3  A: 

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);
ChssPly76
A: 

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

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


Moody