Hibernate异常之 org.hibernate.LazyInitializationException: failed to lazily initialize a collecio....
程序员文章站
2022-03-02 13:25:24
...
1、异常描述
org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role: cn.wang.entity.Clazz.studentSet, no session or session was closed
备注:
此处hibernate版本号:3.6.10.Final
2、示例代码
2-1 实体类
// 学生实体类
public class Student implements Serializable{
private Integer id;
private String name;
private Date birthday;
// 创建关系属性
private Clazz clazz;
// 省略相关代码...
}
// 班级表
public class Clazz implements Serializable{
private Integer id;
private String name;
// 建立关系属性
private Set<Student> studentSet = new HashSet<>();
// 省略部分代码...
2-2 Clazz.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.wang.entity.Clazz" table="hibernate_class" lazy="false">
<!-- 映射主键列 -->
<id name="id" column="id" type="java.lang.Integer">
<!-- 主键由序列生成 -->
<generator class="sequence">
<!-- param中间的值是 序列名 -->
<param name="sequence">hibernate_class_seq</param>
</generator>
</id>
<!-- 映射普通列 方式1:-->
<property name="name" type="java.lang.String" column="name"/>
<!-- 映射关系属性 -->
<set name="studentSet">
<!-- 指定外键列 -->
<key column="cid"></key>
<!-- class="set集合关系属性的泛型" -->
<one-to-many class="cn.wang.entity.Student"/>
</set>
</class>
</hibernate-mapping>
错误原因:
在hibernate中,对于关系属性,默认都是延迟加载机制。所以当我们在session关闭之后,再执行select语句时,就会报此错误
3、解决方式
在Clazz.hbm.xml文件中,设置<set> 的lazy="false" 关闭其延迟加载即可
此文希望可以帮助到大家。如有错误,请指教。
如果大家还有其他的情况或者好的解决方法,也望指教,感谢阅读。
上一篇: python采用的编码
下一篇: 音视频数据库 GRID 爬取
推荐阅读
-
Hiberante异常之org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
问题:org.hibernate.LazyInitializationException: failed to lazily initialize
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of 。。
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.it.
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collect
-
Hibernate异常之 org.hibernate.LazyInitializationException: failed to lazily initialize a collecio....
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
-
org.hibernate.LazyInitializationException: failed to lazily initialize a collection..的解决方案