Hibernate Subquery and DetachedCriteria

dawez picture dawez · May 7, 2010 · Viewed 9.9k times · Source

I have created a DetachedCriteria that is retrieving estates that have the isApproved and isPublished set to true. It is defined in this way:

DetachedCriteria activePublishedCriteria = DetachedCriteria.forClass(Estate.class)
    .add(Restrictions.eq("isApproved", true))
    .add(Restrictions.eq("isPublished", true))
    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

I would like to reuse this criteria in some of the queries. In this case I would like to replace the isApproved and isPublished restrictions with the DetachedCriteria

Criteria criteria = getSession().createCriteria(Estate.class)
       .createAlias("city", "c")
       .add(Restrictions.eq("c.id", cityID))
       // the following 2 lines should use the DetachedCriteria 
       .add(Restrictions.eq("isApproved", true))
       .add(Restrictions.eq("isPublished", true))
       .setProjection(Projections.rowCount());
  return (Integer) criteria.list().get(0);

Is there a way to do this ? Tried to use

.add(Subqueries.geAll(....

But cannot make it work properly. I could not find proper documentation on the Subqueries in Hibernate. Tips are welcomed.

Answer

c0deaddict picture c0deaddict · May 13, 2010

This should work:

.add(Subqueries.geAll(value, detachedCriteria))