org.hibernate.LazyInitializationException: coul...
程序员文章站
2022-03-02 14:13:43
...
1.发生场景
实体对象有对自身的映射。如
package com.amith.office.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.amith.query.QueryObject;
/**
* 文件名:ProcessCategory.java
* 描述:流程分类
* 创建时间:2013-7-24 下午8:55:46
* 创建者:mluo
* 版本号:v1.0
*/
@Entity
@Table(name = "process_categorys")
public class ProcessCategory extends OfficeAggregateRootEntity {
private static final long serialVersionUID = 1L;
private String name;
private ProcessCategory parent;
private Set<ProcessCategory> children = new HashSet<ProcessCategory>();
public ProcessCategory(String name) {
this.name = name;
}
public ProcessCategory() {
}
public void createChild(ProcessCategory child) {
child.setParent(this);
children.add(child);
this.update();
}
public static ProcessCategory getRoot() {
return getRepository().getSingleResult(QueryObject.create(ProcessCategory.class).isNull("parent"));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name = "parent_id")
public ProcessCategory getParent() {
return parent;
}
public void setParent(ProcessCategory parent) {
this.parent = parent;
}
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "process_category_middles", joinColumns = @JoinColumn(name = "parent_id"), inverseJoinColumns = @JoinColumn(name = "child_id"))
public Set<ProcessCategory> getChildren() {
return children;
}
public void setChildren(Set<ProcessCategory> children) {
this.children = children;
}
}
当get某一个对象完了,session已关闭,此时如果调用对象的getChildren()就会出现这个错误。
2. 解决办法
2.1、在相应的映射文件里禁止该类的延迟加载:设置lazy=false
2.2、在session关闭之前取出需要的属性(@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER))
2.3、使用openSessionInView
转载于:https://my.oschina.net/zhuka/blog/147925
推荐阅读
-
错误org.hibernate.LazyInitializationException 博客分类: hibernate HibernateSpringperformanceSQLServlet
-
解决:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
org.hibernate.LazyInitializationException: could not initialize proxy [xxxx] - no Session异常
-
Hiberante异常之org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
【记录】异常:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
org.hibernate.LazyInitializationException: could not initialize proxy 解决方案(JPA)
-
Jpa项目报错:org.hibernate.lazyinitializationexception could not initialize proxy - no session
-
org.hibernate.LazyInitializationException: could not initialize proxy no Session
-
jpa 解决org.hibernate.LazyInitializationException: could not initialize proxy - no Session
-
Spring DATA JPA org.hibernate.LazyInitializationException: could not initialize proxy - no Session