![](/img/trans.png)
[英]SpringBoot + Hibernate JPA Lazy fetching mode still queries lists in an entity
[英]hibernate and jpa weirdness; unexpected lazy fetching
我使用的是Hibernate(3.2.4)的较旧版本,因此可能与此有关。 不幸的是,项目要求使我无法升级。
我有一个与Foo有多对一关联的Foo类。 该关联已标记:
lazy="false" fetch="join"
现在,当我做类似的事情时:
em.find(Foo.class, id);
我得到了预期的结果:将FOO表与BAR表连接在一起的单个语句。 但是,当我尝试类似的东西时:
em.createQuery("select f from Foo where f.id = :id")
.setParameter("id", id)
.getSingleResult();
我得到了单联接,然后是针对BAR的附加选择查询。 第二个查询似乎完全是多余的 ; 急于填充Foo实例所需的所有数据都应该在初始联接中就可用。 大致如下所示:
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 = ?
有什么想法吗?
在执行HQL查询时,Hibernate不尊重fetch = "join"
。 从文档中 :
映射文档中定义的获取策略会影响:
- 通过get()或load()检索
- 导航关联时隐式发生的检索
- 条件查询
- HQL查询是否使用子选择获取
对于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.