Hibernate(JPA)如何做一个渴望的查询,加载所有的子对象 [英] Hibernate (JPA) how to do an eager query, loading all child objects

查看:84
本文介绍了Hibernate(JPA)如何做一个渴望的查询,加载所有的子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于我的前面的问题,我想确保所有子对象被加载,因为我有多个线程可能需要访问数据(从而避免延迟加载异常)。我明白这样做的方法是在查询中使用fetch关键字(EJB QL)。像这样:

 从订单中选择不同的o o左连接读取o.orderLines 

假设一个模型包含一个 OrderLines的 Order 类



我的问题是,distinct关键字似乎是需要的,否则我似乎得到一个 Order 为每个 OrderLine 。我做正确的事情吗?

也许更重要的是,是否有办法拉动所有的子对象,不管它有多深?我们有大约10-15个类,对于服务器,我们将需要加载所有内容......我避免使用 FetchType.EAGER ,因为这意味着它始终渴望并且特别是web前端加载所有内容 - 但也许这是要走的路 - 是你做了什么?我似乎记得我们之前尝试过,然后变得非常缓慢的网页 - 但也许这意味着我们应该使用二级缓存?解决方案

更改注释是一个坏主意IMO。因为它不能在运行时更改为懒惰。更好地使一切都懒惰,并根据需要获取。



我不确定我没有映射理解您的问题。左连接获取应该是您描述的用例所需的全部。当然,如果订单行有一个订单作为其父母,那么您将获得每个订单行的订单。


Relating to my earlier question, I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:

select distinct o from Order o left join fetch o.orderLines

Assuming a model with an Order class which has a set of OrderLines in it.

My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an Order for each OrderLine. Am I doing the right thing?

Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using FetchType.EAGER as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?

解决方案

Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed.

I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.

这篇关于Hibernate(JPA)如何做一个渴望的查询,加载所有的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆