2015-03-03 66 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

相關問題