如何检查 Hibernate 列表以查看它是否已初始化?
在 Hibernate 中,假设您有一个名为“部门”的类,它包含一个员工列表。有没有办法检查员工名单以确定其是否已初始化?似乎无论您访问什么属性,它都会给您带来惰性初始化程序异常。有什么方法可以在不出现异常的情况下测试它的初始化吗?
我想看看它是否已经初始化,如果没有,只需查询数据并填充它。
In Hibernate, let's say you have a class called department and it contains a list of employees. Is there a way to inspect the list of employees to determine if it has been intialized yet? It seems no matter what property you access, it gives you the lazy intializer exception. Is there any way to test it's intialization without getting the exception?
I'd like to see if it has been initializated and if not, just do the query for the data and fill it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Hibernate.isInitialized() 检查 hibernate 实体是否已初始化。
您可以使用 Hibernate.initialize() 强制初始化 hibernate 实体。如果尚未初始化,它会为您查询并填充数据。
You could use Hibernate.isInitialized() to check if the hibernate entity is initialized or not.
You could use Hibernate.initialize() to force initialization for a hibernate entity . It will query and fill the data for you if it is not initializated yet.
您不需要手动执行查询——延迟初始化的全部意义在于,当需要访问数据时,ORM 将为您处理它。
如果您遇到延迟初始化异常,则意味着没有打开休眠会话,因此它无法获取子级。
使用 open-session-in-view (在 Web 应用程序中,它在请求的生命周期内保持会话打开),或者在加载父级时预先初始化集合(这具有加载数据的开销不需要,如果总是需要的话也没关系)。
you shouldn't need to do the query manually -- the entire point of lazy initialization is that the ORM will handle it for you, when it's time to access the data.
If you are getting lazy initialization exception, it means there is no hibernate session open so it can't the fetch children.
Use open-session-in-view (which keeps the session open for the life of the request, in a web app), or initialize the collection up front when the parent is loaded (which has the con of overhead for loading data that might not be needed, which is ok if its always needed).