在我的 Controller 中,我有以下代码获取数据库中的特定表示,将其添加为模型属性并返回详细 View :
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public String detail(Model model, Principal principal, @RequestParam("id") int id) {
Presentation p = presentationDao.get(id);
model.addAttribute("presentation", p);
return "detail";
}
在我看来,我正在尝试使用 JSTL 显示具有延迟加载功能的演示文稿的属性:
${pressentation.student.dossiers.proposal.titel}
但是在 Student 中有一个“文件”列表,但它使用延迟加载:
@OneToMany(mappedBy = "student", fetch = FetchType.LAZY)
private List<Dossier> dossiers;
但我得到以下异常:
org.apache.jasper.JasperException: javax.el.ELException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: domein.Student.dossiers, no session or session was closed
当我将达析报告的 FetchType 设置为 Eager 时,我什至无法运行我的项目:
Severe: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
当我用谷歌搜索时,我找到了以下解决方案:
@RequestMapping(value = "/detail", method = RequestMethod.GET)
public String detail(Model model, Principal principal, @RequestParam("id") int id) {
Presentatie p = presentatieDao.get(id);
Hibernate.initialize(p.getStudent().getDefinitiefDossier().getVoorstel().getTitel());
model.addAttribute("presentatie", p);
return "detail";
}
但它再次给了我以下异常:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: domein.Student.dossiers, no session or session was closed
最佳答案
您的 Controller 没有数据库上下文,因此他不可能获取所有延迟加载数据。您需要做的是直接在 Model 对象(可能是presentatieDao DAO)中编写一个方法,并在将其放入 Controller 之前,通过该方法将所有元素添加到列表中。
关于java - Java Spring 中的延迟加载异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23742474/