Hibernate--QBC离线查询举例+详解(二)

离线查询概述

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);
		
		List<Customer> list = 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]]
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值