2015-03-03 65 views
1

我有一个名为具有父类别字段的类别的表。我正在使用该字段来获取子类别。我已经检查了类似问题的答案,建议是(fetch = FetchType.EAGER)。但我想加载它为LAZY,因为它是循环依赖。 (再次指向同一张表)。org.hibernate.LazyInitializationException:未能长期初始化角色集合

@Entity 
@Table(name = "CATEGORY") 
public class Category implements Serializable { 
    @Id 
    @Column(name = "ID") 
    @GeneratedValue 
    private Integer id; 

    @Column(name = "CATEGORY_NAME", nullable = false, length = 40) 
    private String name; 

    @Column(name = "DESCRIPTION", nullable = false, length = 255) 
    private String description; 

    @Column(name = "DATE_CREATED", nullable = false) 
    private Date dateCreated; 

    @Column(name = "UUID", nullable = false, length = 40) 
    private String uuid; 

    @ManyToOne 
    @JoinColumn(name = "PARENT_CATEGORY_ID") 
    private Category parentCategory; 

    @OneToMany(mappedBy = "parentCategory") 
    private Collection<Category> subCategories = new LinkedHashSet<Category>(); 
} 

的错误是:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.hemanths.expense.manager.api.hibernate.entity.Category.subCategories, could not initialize proxy - no Session 
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566) 
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186) 
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545) 
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124) 
    at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:266) 

有人可以帮助我找到解决办法?

回答

1

看你的堆栈跟踪,看起来这是一个会话管理的问题。试着看看你在哪里打开你的会话,以及你正在使用什么SessionContext?

2

如果您想要获取注释为延迟加载的对象的集合,并且您不想将加载机制转换为渴望,那么您将不得不在同一个sessiontransaction中获取您的集合只要求你收集size()方法,例如在获取它的父对象,如果你有这样的服务方法:

public Category getCategortById(int id) { 
    Category category = categoryDao.getCategortById(id); 
    category.getSubCategories().size(); // Hibernate will fetch the collection once you call the size() 
} 

另外,如果你想为它清洁的方式,你可以使用Hibernate.initalize()方法来初始化任何延迟加载对象或集合,所以它可能是这样的

public Category getCategortById(int id) { 
    Category category = categoryDao.getCategortById(id); 
    Hibernate.initialize(category.getSubCategories()); 
} 

您可以查看更多初始化集合here

+0

感谢您的回复。 如果我说Hibernate.initialize(category.getSubCategories());它不会延迟加载。 而且因为它是相互依赖性,parentCategory将有subCategories,每个子类别将再次拥有parentCategory。它继续无限。 – 2015-03-03 16:48:21

+0

对不起,这是现在发生了什么? – fujy 2015-03-03 18:10:12

+0

是的。这就是为什么我想加载** lazily **。 – 2015-03-04 02:14:41

相关问题