站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Hibernate reference 3.2.0 ga 正式版中文参考手册

15.8. 离线(detached)查询和子查询 - Hibernate reference 3.2.0 ga 正式版中文参考手册

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

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

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

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

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

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

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