异常:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
原因:hibernate3 many-to-one的默认选项是 lazy = "proxy"
解决方法:<many-to-one> 和 <set> 中设置 lazy="false"
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">
<hibernate-mapping>
<class name="po.Emp" table="EMP">
<id name="empno" type="java.lang.Short">
<column name="EMPNO" precision="4" scale="0" />
<generator class="increment" />
</id>
<property name="ename" type="java.lang.String">
<column name="ENAME" length="10" />
</property>
<property name="job" type="java.lang.String">
<column name="JOB" length="9" />
</property>
<property name="mgr" type="java.lang.Short">
<column name="MGR" precision="4" scale="0" />
</property>
<property name="hiredate" type="java.util.Date">
<column name="HIREDATE" length="7" />
</property>
<property name="sal" type="java.lang.Double">
<column name="SAL" precision="7" />
</property>
<property name="comm" type="java.lang.Double">
<column name="COMM" precision="7" />
</property>
<many-to-one name="dept" class="po.Dept" column="DEPTNO" ></many-to-one>
</class>
</hibernate-mapping>
导致异常的原因:
使用HibernateTemplate的save、load等方法时。它的Session管理策略是:打开session。进行相关操作。默认使用lazy载入结果,不会发出sql语句,返回的是代理类,然后关闭session,此时你得到了一个Orgnization的代理类。假设你要调用Orgnization实例的getter方法,那么它就会去实际载入Orgnization对象,发出sql语句,可此时session已经关闭,因此会抛出异常,提示ould not initialize proxy - no Session。