本文共 1455 字,大约阅读时间需要 4 分钟。
DetachedCriteria 翻译为离线条件查询,因为它是可以脱离Session来使用的一种条件查询对象,Criteria对象必须由Session对象来创建。那么也就是说必须先后Session才可以生成Criteria对象。而DetachedCriteria对象可以再其它层对条件进行封装。
这个对象也是比较有用的,尤其在SSH整合以后这个对象会经常使用。它的主要优点是做一些特别复杂的条件查询的时候,往往会在WEB层向业务层传递很多的参数,业务层又会将这些参数传递给DAO层。最后在DAO层拼接SQL完成查询。有了离线条件查询对象后,那么这些工作都可以不用关心了,我们可以在WEB层将数据封装好,传递到业务层,再由业务层传递给DAO完成查询。
如下图:
@Test public void fun1(){ //Service/web层 //创建离线查询对象 DetachedCriteria dc = DetachedCriteria.forClass(Customer.class); dc.add(Restrictions.idEq(1l));//拼装条件(全部与普通Criteria一致) //---------------------------------------------------- Session session = HibernateUtils.openSession(); Transaction tx = session.beginTransaction(); //---------------------------------------------------- //DAO层 关联Session Criteria c = dc.getExecutableCriteria(session); Listlist = c.list(); System.out.println(list); //---------------------------------------------------- tx.commit(); session.close(); }
运行JUnit测试输出:
Hibernate: select this_.cust_id as cust_id1_0_0_, this_.cust_name as cust_nam2_0_0_, this_.cust_source as cust_sou3_0_0_, this_.cust_industry as cust_ind4_0_0_, this_.cust_level as cust_lev5_0_0_, this_.cust_linkman as cust_lin6_0_0_, this_.cust_phone as cust_pho7_0_0_, this_.cust_mobile as cust_mob8_0_0_ from cst_customer this_ where this_.cust_id = ?[Customer [cust_id=1, cust_name=Google, cust_level=2]]
转载地址:http://ajsqb.baihongyu.com/