org.hibernate.LazyInitializationException: 延迟初始化角色集合失败

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

我有 table 称为类别,它有父类别字段。我正在使用该字段来获取子类别。我已经检查了类似问题的答案,建议是(fetch = FetchType.EAGER)。但是我想将它加载为 LAZY 因为它是循环依赖。 (再次指向同一个 table)。

@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)

谁能帮我找到解决办法?

如果你想获取一个被注释为惰性加载的对象集合并且你不想将加载机制转换为急切的,那么你将不得不在同一个集合中获取集合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

查看您的堆栈跟踪,这似乎是一个会话管理问题。尝试查看您打开会话的位置,以及您使用的是什么 SessionContext?