hibernate many to one查询时执行的sql是cross join如何变成left join

 我来答
山水阿锐
2015-05-29 · TA获得超过34.3万个赞
知道顶级答主
回答量:23.7万
采纳率:91%
帮助的人:3.3亿
展开全部
left join fetch可以取出lazy对象,当你在设置lazy=true时,取对象的时候会使用延迟加载。但是你可以使用left join fetch强制取出lazy对象。设置成lazy="false"当然就不需要fetch了。
1、outer-join关键字(many-to-one的情况)
outer-join关键字有3个值,分别是true,false,auto,默认是auto。
true: 表示使用外连接抓取关联的内容,这里的意思是当使用load(OrderLineItem.class,"id")时,Hibernate只生成一条SQL语句将OrderLineItem与他的父亲Order全部初始化。
select * from OrderLineItem o left joinOrderpon o.OrderId=p.OrderId where o.OrderLineItem_Id=?
false:表示不使用外连接抓取关联的内容,当load(OrderLineItem.class,"id")时,Hibernate生成两条SQL语句,一条查询OrderLineItem表,另一条查询Order表。这样的好处是可以设置延迟加载,此处要将Order类设置为lazy=true。
select * from OrderLineItem owhere o.OrderLineItem_Id=?
select * from Order p where p.OrderId=?
auto:具体是ture还是false看hibernate.cfg.xml中的配置
注意:如果使用HQL查询OrderLineItem,如 from OrderLineItem o where o.id='id',总是不使用外部抓取,及outer-join失效。
2、outer-join(集合)
由于集合可以设置lazy="true",所以lazy与outer-join不能同时为true,当lazy="true"时,outer-join将一直是false,如果lazy="false",则outer-join用法与1同
3、HQL语句会将POJO配置文件中的关联一并查询,即使在HQL语句中没有明确join。
4、In HQL, the "fetch join" clause can be used for per-query specific outer join fetching. One important thing many people miss there, is that HQL queries will ignore the outer-join attribute you specified in your mapping. This makes it possible to configure the default loading behaviour of session.load() and session.get() and of objects loaded by navigating relationship. So if you specify
and then do
MyObject obj = session.createQuery("from MyObject").uniqueResult();
obj.getMySet().iterator().next();
you will still have an additional query and no outer-join. So you must explicily request the outer-join fetching:
MyObject obj = session.createQuery(
"from MyObject mo left join fetch mo.mySet").uniqueResult();
obj.getMySet().iterator().next();
Another important thing to know is that you can only fetch one collection reference in a query. That means you can just use one fetch join. You can however fetch "one" references in addition, as this sample from the Hibernate Docs demonstrates:
from eg.Cat as cat
inner join fetch cat.mate
left join fetch cat.kittens
We have once considered lifting this limitation, but then decided against it, because using more than one fetch-join would be a bad idea generally: The generated ResultSet becomes huge and is a major performance loss.
So alltogether the "fetch join" clause is an important instrument Hibernate users should learn how to leverage, as it allows tuning the fetch behaviour of a certain use case.
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式