---
title: "hibernate延迟加载（load、get区别）"
author: "liweitsky"
date: "2011-01-21T14:55:10Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-load-get"
draft: false
lastmod: "2011-01-21T14:55:10Z"
id: 890901
url: "https://liweitsky.iteye.com/blog/890901"
---

由于Spring控制的Hibernate的生命周期只针对数据层和服务层，而未管理到表现层，所以在表现层使用延时加载会出现the owning Session was closed或者no session or session was closed的异常信息。针对这一点，可以通过hibernate filter的方式来解决。

在WEB.xml文件中配置filter.

```java
<!-- hibernate session 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<span style="color:red">（注：这个plugin似乎对编码也有影响，需要用spring的过滤器、自己写的过滤器达不到效果，以后测试完了，分析下）</span>

```java
<plug-in
    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里加上如下代码：

```java
<!--Spring ApplicationContext-->
<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中加入一个参数
<init-param>
    <param-name>singleSession</param-name>
    <param-value>true</param-value>
</init-param>
就可以了，当然这样 每次访问dao都会新开个session，对性能的影响还是比较大的。最好的办法当然是<span style="color:red">配置事务</span>了。

配置说完了，下面介绍下延迟加载的优缺点，即getHibernateTemplate.load() 和get()之间的区别
主要的地方：
getHibernateTemplate.load() 存在延迟加载问题。
getHibernateTemplate.get() 不存在此问题，不采用lazy机制的。
1 当记录不存在时候，get方法返回null,load方法产生异常，即get()可以取空的数据集,但load()不行。  
2 load方法可以返回实体的代理类，get方法则返回真是的实体类
3 load方法可以充分利用hibernate的内部缓存和二级缓存中的现有数据，而get方法仅仅在内部缓存中
进行数据查找，如果没有发现数据則将越过二级缓存，直接调用SQL查询数据库。
4 也许别人把数据库中的数据修改了，load如何在缓存中找到了数据，则不会再访问数据库，而get则
会返回最新数据。