Hibernate 5 延迟加载问题
Hibernate 5 Lazy Loading Issue
我有一个 class 的用户有一个项目列表(集合):
@OneToMany(mappedBy = "user_owner_id")
private Collection<Project> project = new ArrayList<>();
有时,我想查看项目列表并获取它们:
Session sessionF = sessionFactory.openSession();
sessionF.beginTransaction();
user = sessionF.get(User.class, user.getId());
sessionF.getTransaction().commit();
List<Project> projects = (List<Project>) user.getProject();
sessionF.close();
如果我不使用 projects
做某事,它会抛出错误:org.hibernate.LazyInitializationException: could not initialize proxy – no Session
但是如果我添加 int projectCount = projects.size();
它就可以正常工作。为什么会发生这种情况,如果不在此处玩 projects
如何解决它?
P.S。在我关闭会话后,我只是通过 HttpServletRequest
传递它,然后在 jsp
文件中用 for 循环遍历它。
查看 Hibernate 参考文档的 Fetching Strategies 部分
Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
从实体返回您的集合并将其分配给变量不涉及对该集合调用方法。
我有一个 class 的用户有一个项目列表(集合):
@OneToMany(mappedBy = "user_owner_id")
private Collection<Project> project = new ArrayList<>();
有时,我想查看项目列表并获取它们:
Session sessionF = sessionFactory.openSession();
sessionF.beginTransaction();
user = sessionF.get(User.class, user.getId());
sessionF.getTransaction().commit();
List<Project> projects = (List<Project>) user.getProject();
sessionF.close();
如果我不使用 projects
做某事,它会抛出错误:org.hibernate.LazyInitializationException: could not initialize proxy – no Session
但是如果我添加 int projectCount = projects.size();
它就可以正常工作。为什么会发生这种情况,如果不在此处玩 projects
如何解决它?
P.S。在我关闭会话后,我只是通过 HttpServletRequest
传递它,然后在 jsp
文件中用 for 循环遍历它。
查看 Hibernate 参考文档的 Fetching Strategies 部分
Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
从实体返回您的集合并将其分配给变量不涉及对该集合调用方法。