[英]hibernate and jpa weirdness; unexpected lazy fetching
I'm using a rather old version of Hibernate (3.2.4) so it's possible this is related to that. 我使用的是Hibernate(3.2.4)的较旧版本,因此可能与此有关。 Unfortunately the project requirements prevent me from upgrading.
不幸的是,项目要求使我无法升级。
I have a class Foo with many-to-one association to Bar. 我有一个与Foo有多对一关联的Foo类。 The association is flagged:
该关联已标记:
lazy="false" fetch="join"
Now when I do something like: 现在,当我做类似的事情时:
em.find(Foo.class, id);
I get the expected result: a single statement joining the FOO table with the BAR table. 我得到了预期的结果:将FOO表与BAR表连接在一起的单个语句。 However, when I try something like:
但是,当我尝试类似的东西时:
em.createQuery("select f from Foo where f.id = :id")
.setParameter("id", id)
.getSingleResult();
I get the single join followed by an additional select query against BAR. 我得到了单联接,然后是针对BAR的附加选择查询。 The second query seems to be entirely superfluous ;
第二个查询似乎完全是多余的 ; all the data needed to eagerly populate an instance of Foo should have been available from the initial join.
急于填充Foo实例所需的所有数据都应该在初始联接中就可用。 It looks roughly like this:
大致如下所示:
select f.id, f.xyz, ..., b.id, b.xyz, ...
from foo f
join bar b on b.id = f.bar_id
where f.id = ?
select b.id, b.xyz, ...
from bar b
where b.id = ?
Any thoughts? 有什么想法吗?
Hibernate doesn't respect fetch = "join"
when executing HQL queries. 在执行HQL查询时,Hibernate不尊重
fetch = "join"
。 From the documentation : 从文档中 :
The fetch strategy defined in the mapping document affects:
映射文档中定义的获取策略会影响:
- retrieval via get() or load()
通过get()或load()检索
- retrieval that happens implicitly when an association is navigated
导航关联时隐式发生的检索
- Criteria queries
条件查询
- HQL queries if subselect fetching is used
HQL查询是否使用子选择获取
In the case of HQL queries you have to use left join fetch
: 对于HQL查询,您必须使用
left join fetch
:
em.createQuery("select f from Foo f left join fetch f.bar where f.id = :id")
.setParameter("id", id)
.getSingleResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.