Hibernate join fetch会执行N + 1,如何解决? [英] Hibernate join fetch does an N+1, how to fix it?

查看:77
本文介绍了Hibernate join fetch会执行N + 1,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询:

@NamedQuery(
        name = "org.mygovscot.stars.model.UserNeed.findAll", query =
            "SELECT un FROM UserNeed un " +
            "LEFT JOIN FETCH un.services "
    )

从服务到UserNeed的这种映射:

With this mapping from Service to UserNeed:

<set name="userNeeds" table="service_userNeed">
  <key column="service_id"/>
  <many-to-many column="userNeed_id" class="UserNeed"/>
</set>

以及从UserNeed到Service的映射:

and this mapping from UserNeed to Service:

<set name="services" table="service_userNeed">
  <key column="userNeed_id"/>
  <many-to-many column="service_id" class="Service"/>
</set>

也就是说,它是双向的多对多.

That is, its a bi-directional many-to-many.

我这样查询它:

currentSession()
    .getNamedQuery("org.mygovscot.stars.model.UserNeed.findAll")
    .list();

我的理解是,"join fetch"将热切地获取关联,从而避免进行N + 1查询.但是,结果是Hibernate执行N + 1来获取所有UserNeeds.

My understanding was that a "join fetch" would eagerly fetch associations, thereby avoiding doing an N+1 query. However, the result is that Hibernate does an N+1 to fetch all the UserNeeds.

这是怎么回事? UserNeed还与其他实体有一些关联,我没有包含在联接获取中,我是否还需要联接获取它们才能在单个查询中完成所有操作?

What does this happen? The UserNeed also has some associations with other entities, which I have not included in the join fetch, do I also need to join fetch them to do it all in a single query?

推荐答案

在查询中将其他关联的集合添加为"join fetches",从而对其进行了修复,整个过程在1个查询中运行.我认为使用查询会覆盖默认的获取策略,但是事实是,在没有其他关系获取联接的情况下,Hibernate对待它们的方式有所不同.

Adding the other associated collection as 'join fetches' in the query fixed it, and the whole thing ran in 1 query. I think using a query overrides the default fetch strategy, but the fact that there were other relations in there not being join fetched meant that Hibernate treated them differently.

我仍然有兴趣听到有关调整获取策略是否也有帮助的意见,也就是说,我是否应该将获取策略设置为"join"?无论如何,N + 1现在可以以一种或另一种方式固定.

I would be interested still to hear comments on whether adjuting the fetch strategy might also help, that is, should I have set the fetching strategy to 'join'? Anyway the N+1 is now fixed one way or another.

这篇关于Hibernate join fetch会执行N + 1,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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