我有这样的实例:
@Entity
@Table(name = "ASSESSMENT")
public class Assessment {
//All other fields..
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "assessment")
@OrderBy(value = "order ASC")
private List<AssessmentPart> assessmentParts = new LinkedList<>();
public List<AssessmentPart> getAssessmentParts() {
return assessmentParts;
}
//All other getters/setters
}
另一个例子:
@Entity
@Table(name = "ASSESSMENT_PART")
public class AssessmentPart {
//All other fields
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ASSESSMENT_ID", nullable = false)
private Assessment assessment;
public Assessment getAssessment() {
return assessment;
}
public void setAssessment(Assessment assessment) {
this.assessment = assessment;
}
//All other getters/setters
}
评估部分从评估实体进行延迟加载。我还有一个Spring控制器方法,它是Transactional的,并从数据库加载评估部分:
@Transactional
public void doSomething(String partId, Map<String, Object> model) {
AssessmentPart assessmentPart = //laods a part with entity manager
Assessment assessment = assessmentPart.getAssessment(); //Getting the assessments
model.put("assessmentParts", assessment.getAssessmentParts()); //adding all assessments parts into spring model map
}
一旦我将评估部分添加到Spring模型映射中,它们就会在我的JSP页面中可用,并且我使用JSTL循环遍历它们:
<c:forEach var="assessmentPart" items="${assessmentParts}">
//Not loading any lazy stuff, just getting an ID of assessment part
</c:forEach>
该异常是从此JSP页面抛出的:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: my.package.something.Assessment.assessmentParts, could not initialize proxy - no Session
如果这个集合已经在事务中被加载了,那么这怎么可能呢?我只是想循环遍历,此时Hibernate不应该再加载任何东西,因为它已经加载了。为什么会发生这种奇怪的事情呢?
OpenSessionInViewFilter
或者 使用Hibernate.initialize
方法来正确初始化该集合。 - M. Deinum