我有 3 个实体,分别命名为Discipline、DisciplineMembership、DisciplineManagement:
一个Discipline有很多DisciplineMemberships
一个Discipline有很多DisciplineManagements
一个DisciplineManagement 与 DisciplineMembership有一对一的关系
Discipline 的相关 hbm 文件的相关部分如下所示:
纪律.hbm:
<class name="Discipline" table="DISCIPLINES">
<id name="id" type="java.lang.Long">
<generator class="increment" />
</id>
<set name="memberships" inverse="false" cascade="all-delete-orphan" >
<key column="disciplineId" not-null="true" />
<one-to-many class="DisciplineMembership" />
</set>
<set name="managements" inverse="false" cascade="all-delete-orphan">
<key column="disciplineId" not-null="true" />
<one-to-many class="DisciplineManagement" />
</set>
</class>
在一个名为A的函数中,我想遍历一个 Discipline 的 DisciplineMemberships 和 DiscipilineManagements:
public void A(){
Discipline discipline = this.getObject();
for(DisciplineMembership mem: discipline.getMembers()){
System.out.print(mem);
}
for(DisciplineManagement man: discipline.getManagements()){
System.out.print(man);
}
}
第一个for语句运行正确,但在第二个中,我捕获 LazyInitializationException 如下:
13-04-27 13:54:26,115 [hibernate.LazyInitializationException (<init>:42)] ERROR: failed to lazily initialize a collection of role: Discipline.managements, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: Discipline.managements, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
at org.hibernate.collection.PersistentSet.iterator(PersistentSet.java:186)
at ObjectManagementPart_Edit.A(ObjectManagementPart_Edit.java:6)
我很困惑这怎么可能?Discipline Session 是打开的,我可以遍历它的成员,但是当我想遍历它的管理时,hibernate 不能lazyInitialize 它们。
我应该怎么办?
更新: 我尝试使用 Hibernate.initialize() 函数,所以函数 A 现在是这样的:
public void A(){
Discipline discipline = this.getObject();
Hibernate.initialize(discipline.getMembeships());
for(DisciplineMembership mem: discipline.getMemberships()){
System.out.print(mem);
}
Hibernate.initialize(discipline.getManagements());
for(DisciplineManagement man: discipline.getManagements()){
System.out.print(man);
}
}
第一次将 Hibernate.initialize() 用于Membeships没有问题,但在第二次用于管理时,我得到了这个异常:
org.hibernate.HibernateException: collection is not associated with any session
at org.hibernate.collection.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:474)
at org.hibernate.Hibernate.initialize(Hibernate.java:431)
at discipline.ObjectManagementPart_Edit.A(ObjectManagementPart_Edit.java:6)
现在我更困惑了:/