org.hibernate.LazyInitializationException: coul...

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


你可能感兴趣的:(java,Hibernate)