15.8. 离线(detached)查询和子查询

DetachedCriteria类使你在一个session范围之外创建一个查询,并且可以使用任意的 Session来执行它。

  1. DetachedCriteria query = DetachedCriteria.forClass(Cat.class)
  2. .add( Property.forName("sex").eq('F') );
  3. Session session = ....;
  4. Transaction txn = session.beginTransaction();
  5. List results = query.getExecutableCriteria(session).setMaxResults(100).list();
  6. txn.commit();
  7. session.close();

DetachedCriteria也可以用以表示子查询。条件实例包含子查询可以通过 Subqueries或者Property获得。

  1. DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
  2. .setProjection( Property.forName("weight").avg() );
  3. session.createCriteria(Cat.class)
  4. .add( Property.forName("weight).gt(avgWeight) )
  5. .list();
  1. DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
  2. .setProjection( Property.forName("weight") );
  3. session.createCriteria(Cat.class)
  4. .add( Subqueries.geAll("weight", weights) )
  5. .list();

甚至相互关联的子查询也是有可能的:

  1. DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Cat.class, "cat2")
  2. .setProjection( Property.forName("weight").avg() )
  3. .add( Property.forName("cat2.sex").eqProperty("cat.sex") );
  4. session.createCriteria(Cat.class, "cat")
  5. .add( Property.forName("weight).gt(avgWeightForSex) )
  6. .list();