强制预先加载原本延迟加载的属性
我有一个 Hibernate 对象,它的属性都是惰性加载的。大多数这些属性是其他 Hibernate 对象或 PersistentSet。
现在我想强制 Hibernate 一次性加载这些属性。
当然,我可以使用 object.getSite().size()“触摸”每个属性,但也许还有另一种方法可以实现我的目标。
I've got a Hibernate object which's properties are all loaded lazy. Most of these properties are other Hibernate objects or PersistentSets.
Now I want to force Hibernate to eager load these properties for just one time.
Of course I could "touch" each of these properties with object.getSite().size()
but maybe there's another way to achieve my goal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是一个老问题,但我还想指出静态方法
Hibernate.initialize
。用法示例:
即使在会话关闭后,子级现在也已初始化为可以使用。
This is an old question, but I also wanted to point out the static method
Hibernate.initialize
.Example usage:
The children are now initialized to be used even after the session is closed.
文档是这样描述的:
参考资料
The documentation puts it like this:
References
Dozer 非常适合这种类型的事情 - 您可以要求 Dozer 将对象映射到同一对象的另一个实例类,Dozer 将访问当前对象可到达的所有对象。
请参阅类似问题的答案和我对另一个相关问题的回答了解更多详细信息。
Dozer works well for this type of thing - you can ask Dozer to map the object to another instance of the same class, and Dozer will visit all objects reachable from the current object.
See this answer to a similar question and my answer to another related question for more details.
对我来说这有效:
而不是这样:
For me this works:
Rather than this:
3种方式
1.带有左连接子级的
HQL 2.createCriteria之后的SetFetchMode
3.Hibernate.initialize
3 ways
1.HQL with left join children
2.SetFetchMode after createCriteria
3.Hibernate.initialize
这很慢,因为它会为需要初始化的每个项目进行往返,但它完成了工作。
This is slow, because it makes a round trip for every item it needs to initialize, but it gets the job done.
自从提出这个问题以来已经过去了十年,但我也遇到了这个问题。我注意到,如果您使用 Spring,使用 org.springframework.transaction.annotation.Transactional 注释该方法可以很好地解决这个问题。
示例
不起作用,抛出异常。但
有效。
A decade has passed since this question was asked, but I bumped into this problem as well. I noticed that if you are using Spring, annotating the method with
org.springframework.transaction.annotation.Transactional
solves it nicely.Example
doesn't work, exception thrown. But
works.
根据 hibernate 文档,你应该能够通过在特定属性映射上设置
lazy
属性来禁用延迟属性加载:According to the hibernate docs, you should be able to disable lazy property loading by setting the
lazy
attribute on your particular property mappings: