Hibernate与延迟加载: Hibernate对象关系映射提供延迟的与非延迟的对象初始化。非延迟加载在读取一个对象的时候会将与这个对象所有相关的其他对象一起读取出来。这有时会导致成百的(如果不是成千的话) select 语句在读取对象的时候执行。这个问题有时出现在使用双向关系的时候,经常会导致整个数据库都在初始化的阶段被读出来了。当然,你可以不厌其烦地检查每一个对象与其他对象的关系,并把那些最昂贵的删除,但是到最后,我们可能会因此失去了本想在 ORM 工具中获得的便利。
一个明显的解决方法是使用 Hibernate 提供的延迟加载机制。这种初始化策略只在一个对象调用它的一对多或多对多关系时才将关系对象读取出来。这个过程对开发者来说是透明的,而且只进行了很少的数据库操作请求,因此会得到比较明显的性能提升。这项技术的一个缺陷是延迟加载技术要求一个 Hibernate 会话要在对象使用的时候一直开着。这会成为通过使用 DAO 模式将持久层抽象出来时的一个主要问题。为了将持久化机制完全地抽象出来,所有的数据库逻辑,包括打开或关闭会话,都不能在应用层出现。最常见的是,一些实现了简单接口的 DAO 实现类将数据库逻辑完全封装起来了。一种快速但是笨拙的解决方法是放弃 DAO 模式,将数据库连接逻辑加到应用层中来。这可能对一些小的应用程序有效,但是在大的系统中,这是一个严重的设计缺陷,妨碍了系统的可扩展性。
在 Web 层进行延迟加载 幸运的是, Spring 框架为 Hibernate 延迟加载与 DAO 模式的整合提供了一种方便的解决方法。对那些不熟悉 Spring 与 Hibernate 集成使用的人,我不会在这里讨论过多的细节,但是我建议你去了解 Hibernate 与 Spring 集成的数据访问。以一个 Web 应用为例, Spring 提供了 OpenSessionInViewFilter 和 OpenSessionInViewInterceptor 。我们可以随意选择一个类来实现相同的功能。两种方法唯一的不同就在于 interceptor 在 Spring 容器中运行并被配置在 web 应用的上下文中,而 Filter 在 Spring 之前运行并被配置在 web.xml 中。不管用哪个,他们都在请求将当前会话与当前(数据库)线程绑定时打开 Hibernate 会话。一旦已绑定到线程,这个打开了的 Hibernate 会话可以在 DAO 实现类中透明地使用。这个会话会为延迟加载数据库中值对象的视图保持打开状态。一旦这个逻辑视图完成了, Hibernate 会话会在 Filter 的 doFilter 方法或者 Interceptor 的 postHandle 方法中被关闭。下面是每个组件的配置示例:
Interceptor的配置:
<beans>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInViewInterceptor"/>
</list>
</property>
<property name="mappings">
...
</bean>
...
<bean name="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
</beans>
Filter的配置
<web-app>
...
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</filter-class>
</filter>
...
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*. spring </url-pattern>
</filter-mapping>
...
</web-app>
由于Spring控制的Hibernate的生命周期只针对数据层和服务层,而未管理到表现层,所以在表现层使用延时加载会出现the owning Session was closed或者no session or session was closed的异常信息。针对这一点,可以通过hibernate filter的方式来解决。
在WEB.xml文件中配置filter.
< filter >
< filter-name > OpenSessionInViewFilter </ filter-name >
< filter-class >
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</ filter-class >
</ filter >
< filter-mapping >
< filter-name > OpenSessionInViewFilter </ filter-name >
< url-pattern > *.do </ url-pattern >
</ filter-mapping >
我们的系统架构是struts+spring+hibernate,struts跟spring的整合是在struts-config.xml里加了个plugin
className ="org.springframework.WEB.struts.ContextLoaderPlugIn" >
< set-property property ="contextConfigLocation"
value ="/WEB-INF/classes/applicationContext.xml" />

</ plug-in >
在WEB.xml中配置hibernateFilter 后,还需要在struts-config.xml里把plugin去掉,在WEB.xml里加上如下代码:
< context-param >
< param-name > contextConfigLocation </ param-name >
< param-value > /WEB-INF/classes/applicationContext.xml </ param-value >
</ context-param >
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener
</ listener-class >
</ listener >
这样配置之后如果没有配置事务,是有问题的。不能进行update和insert操作了。
怎么办呢?只需要在filter中加入一个参数
< param-name > singleSession </ param-name >
< param-value > true </ param-value >
</ init-param >
就可以了,当然这样 每次访问dao都会新开个session,对性能的影响还是比较大的。最好的办法当然是配置事务了。
Team.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="edu.dgut.ke.model.Team" table="TEAM" lazy ="true" ><!-- 多对一的延迟加载设置 -->
<id name="id" type="java.lang.String">
<column name="ID" length="32" />
<generator class="uuid.hex" />
</id>
<property name="teamname" type="java.lang.String">
<column name="TEAMNAME" length="32" not-null="true" unique="true" />
</property>
<set name="students" inverse="true" cascade="all" lazy="true" > <!-- 一对多的延迟加载设置 -->
<key>
<column name="TEAMID" length="32" not-null="true" />
</key>
<one-to-many class="edu.dgut.ke.model.Student" />
</set>
</class>
</hibernate-mapping>
Certificate.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="edu.dgut.ke.model.Certificate" table="CERTIFICATE" lazy="true" ><!-- 一对一的延迟加载设置 -->
<id name="id" type="java.lang.String">
<column name="ID" length="32" />
<generator class="uuid">
</generator>
</id>
<property name="describe" type="java.lang.String">
<column name="`DESCRIBE`" length="50" not-null="true" />
</property>
<one-to-one name="student"
class="edu.dgut.ke.model.Student"
constrained="true" ><!-- 一对一的延迟加载设置 -->
</one-to-one>
</class>
</hibernate-mapping>
Student.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="edu.dgut.ke.model.Student" table="STUDENT" lazy="true" >
<id name="id" type="java.lang.String">
<column name="ID" length="32" />
<generator class="uuid.hex" />
</id>
<many-to-one name="certificate"
class="edu.dgut.ke.model.Certificate"
unique="true"
column="cardId"
cascade="all"
>
</many-to-one>
<many-to-one name="team" class="edu.dgut.ke.model.Team">
<column name="TEAMID" length="32" not-null="true" />
</many-to-one>
<property name="studentname" type="java.lang.String">
<column name="STUDENTNAME" length="16" not-null="true" unique="true" />
</property>
</class>
</hibernate-mapping>
注意:对one-to-one 关系进行延迟加载和其他关系相比稍微有些不同。many-to-one 的延迟加载是在配置文件的class 标签
上设置 lazy="true" ,one-to-many 和 many-to-many 的延迟加载是在 set 标签中设置lazy="true"。而one-to-one 不只要在 classs
标签设置 lazy="true",而且要在one-to-one 标签中设置constrained="true" 。
如果不设置constrained="true",则一对一查询使用默认的预先抓取策略(fetch="join")。
详细出处参考:http://www.jb51.net/article/16039.htm
延迟初始化错误是运用Hibernate开发项目时最常见的错误。如果对一个类或者集合配置了延迟检索策略,那么必须当代理类实例或代理集合处于持久化状态(即处于Session范围内)时,才能初始化它。如果在游离状态时才初始化它,就会产生延迟初始化错误。
下面把Customer.hbm.xml文件的<class>元素的lazy属性设为true,表示使用延迟检索策略:
- <class name="mypack.Customer" table="CUSTOMERS" lazy="true">
当执行Session的load()方法时,Hibernate不会立即执行查询CUSTOMERS表的select语句,仅仅返回Customer类的代理类的实例,这个代理类具由以下特征:
(1) 由Hibernate在运行时动态生成,它扩展了Customer类,因此它继承了Customer类的所有属性和方法,但它的实现对于应用程序是透明的。
(2) 当Hibernate创建Customer代理类实例时,仅仅初始化了它的OID属性,其他属性都为null,因此这个代理类实例占用的内存很少。
(3)当应用程序第一次访问Customer代理类实例时(例如调用customer.getXXX()或customer.setXXX()方法), Hibernate会初始化代理类实例,在初始化过程中执行select语句,真正从数据库中加载Customer对象的所有数据。但有个例外,那就是当应用程序访问Customer代理类实例的getId()方法时,Hibernate不会初始化代理类实例,因为在创建代理类实例时OID就存在了,不必到数据库中去查询。
提示:Hibernate采用CGLIB工具来生成持久化类的代理类。CGLIB是一个功能强大的Java字节码生成工具,它能够在程序运行时动态生成扩展 Java类或者实现Java接口的代理类。关于CGLIB的更多知识,请参考:http://cglib.sourceforge.net/。
以下代码先通过Session的load()方法加载Customer对象,然后访问它的name属性:
- tx = session.beginTransaction();
- Customer customer=(Customer)session.load(Customer.class,new Long(1));
- customer.getName();
- tx.commit();
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
customer.getName();
tx.commit();
在运行session.load()方法时Hibernate不执行任何select语句,仅仅返回Customer类的代理类的实例,它的OID为1,这是由load()方法的第二个参数指定的。当应用程序调用customer.getName()方法时,Hibernate会初始化Customer代理类实例,从数据库中加载Customer对象的数据,执行以下select语句:
- select * from CUSTOMERS where ID=1;
- select * from ORDERS where CUSTOMER_ID=1;
select * from CUSTOMERS where ID=1;
select * from ORDERS where CUSTOMER_ID=1;
当<class>元素的lazy属性为true,会影响Session的load()方法的各种运行时行为,下面举例说明。
1.如果加载的Customer对象在数据库中不存在,Session的load()方法不会抛出异常,只有当运行customer.getName()方法时才会抛出以下异常:
ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.ObjectNotFoundException: No row with the given identifier exists: 1, of class:
mypack.Customer
2.如果在整个Session范围内,应用程序没有访问过Customer对象,那么Customer代理类的实例一直不会被初始化,Hibernate不会执行任何select语句。以下代码试图在关闭Session后访问Customer游离对象:
- tx = session.beginTransaction();
- Customer customer=(Customer)session.load(Customer.class,new Long(1));
- tx.commit();
- session.close();
- customer.getName();
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
tx.commit();
session.close();
customer.getName();
由于引用变量customer引用的Customer代理类的实例在Session范围内始终没有被初始化,因此在执行customer.getName()方法时,Hibernate会抛出以下异常:
ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Could not initialize proxy - the owning Session was closed
由此可见,Customer代理类的实例只有在当前Session范围内才能被初始化。
3.net.sf.hibernate.Hibernate类的initialize()静态方法用于在Session范围内显式初始化代理类实例,isInitialized()方法用于判断代理类实例是否已经被初始化。例如:
- tx = session.beginTransaction();
- Customer customer=(Customer)session.load(Customer.class,new Long(1));
- if(!Hibernate.isInitialized(customer))
- Hibernate.initialize(customer);
- tx.commit();
- session.close();
- customer.getName();
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
if(!Hibernate.isInitialized(customer))
Hibernate.initialize(customer);
tx.commit();
session.close();
customer.getName();
以上代码在Session范围内通过Hibernate类的initialize()方法显式初始化了Customer代理类实例,因此当Session关闭后,可以正常访问Customer游离对象。
4.当应用程序访问代理类实例的getId()方法时,不会触发Hibernate初始化代理类实例的行为,例如:
- tx = session.beginTransaction();
- Customer customer=(Customer)session.load(Customer.class,new Long(1));
- customer.getId();
- tx.commit();
- session.close();
- customer.getName();
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
customer.getId();
tx.commit();
session.close();
customer.getName();
当应用程序访问customer.getId()方法时,该方法直接返回Customer代理类实例的OID值,无需查询数据库。由于引用变量 customer始终引用的是没有被初始化的Customer代理类实例,因此当Session关闭后再执行customer.getName()方法, Hibernate会抛出以下异常:
ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Could not initialize proxy - the owning Session was closed
解决方法:
由于hibernate采用了lazy=true,这样当你用hibernate查询时,返回实际为利用cglib增强的代理类,但其并没有实际填充;当你在前端,利用它来取值(getXXX)时,这时Hibernate才会到数据库执行查询,并填充对象,但此时如果和这个代理类相关的session已关闭掉,就会产生种错误.
在做一对多时,有时会出现"could not initialize proxy - clothe owning Session was sed,这个好像是hibernate的缓存问题.问题解决:需要在<many-to-one>里设置lazy="false". 但有可能会引发另一个异常叫
failed to lazily initialize a collection of role: XXXXXXXX, no session or session was closed
解决方法:在web.xml中加入
- <filter>
- <filter-name>hibernateFilter</filter-name>
- <filter-class>
- org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
- </filter-class>
- </filter
- <filter-mapping>
- <filter-name>hibernateFilter</filter-name>
- <url-pattern>*.do</url-pattern>
- </filter-mapping>
就可以了;