Hibernate-04 延迟加载

学习任务

  • 延迟加载
  • Open Session In View模式

延迟加载

延迟加载(lazy load懒加载)是在真正需要数据时才执行SQL语句进行查询,避免了无谓的性能开销。

延迟加载策略的设置分为:类级别的查询策略、一对多和多对多关联的查询策略、多对一关联的查询策略。

Hibernate3.X以上的版本,默认都是采用延迟加载策略。

用于设定延迟加载特性的lazy属性如下表所示:

级别 lazy属性取值
类级别 <class>元素中lazy属性的可选值为true(延迟加载)和false(立即加载)。默认值为true。
一对多关联级别 <set>元素中lazy属性的可选值为true(延迟加载)、extra(增强延迟加载)和fasle(立即加载)。默认值为true。
多对一关联级别 <many-to-one>元素中的lazy属性的可选值为proxy(延迟加载)、no-proxy(无代理延迟加载)和false(立即加载)。默认为proxy。

类级别查询策略

类级别可选策略有:立即加载和延迟加载。默认为延迟加载。

一、立即加载

 1.Dept.hbm.xml文件

	<class name="com.etc.entity.Dept" table="`DEPT`" schema="scott"
		dynamic-update="true" lazy="false">

  

2.DAO代码

return (Dept) this.getSession().load(Dept.class, id);

  

3.BIZ测试方法

	@Test
	public void load() {
		Transaction tx=null;
		try{
			tx=deptDao.getSession().beginTransaction();
			Dept dept=deptDao.load(new Short("10"));
			tx.commit();		
			System.out.println(dept.getDeptName());//事务关闭,确认dept属性已全部加载,并输出部门名称
		}catch (Exception e) {
			e.printStackTrace();
			if(tx!=null){
				tx.rollback();
			}
		}
	}

  

4.测试结果

Hibernate: 
    select
        dept0_."DEPTNO" as DEPTNO1_0_0_,
        dept0_."DNAME" as DNAME2_0_0_,
        dept0_."LOC" as LOC3_0_0_ 
    from
        scott."DEPT" dept0_ 
    where
        dept0_."DEPTNO"=?

  

备注:load()方法默认加载OID,不加载实体属性。假如修改class的lazy属性值为true,若要在session关闭后输出实体属性(例外:访问OID不会引发数据库查询,不会报错),将会报如下错误:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

  

此外,无论类级别设置是否为延迟加载,get()和list()方法都是立即加载。

二、延迟加载

1.映射文件延迟加载设置

	<class name="com.etc.entity.Dept" table="`DEPT`" schema="scott"
		dynamic-update="true" lazy="true">

  或者:

	<class name="com.etc.entity.Dept" table="`DEPT`" schema="scott"
		dynamic-update="true">

  

//待续

一对多和多对多关联查询策略

多对一关联查询策略

Open Session In View

猜你喜欢

转载自www.cnblogs.com/rask/p/8706396.html
今日推荐