Hibernate 集合以最佳方式获取
我有以下结构
商店
回扣
回扣元数据
RebateCommission
那么,关系是这样的 -
Store ->回扣是一对多的关系 返利-> RebateMetadata 是一对一的映射 返利-> RebateCommission 是一对一映射,
我的查询是加载所有商店。并用它加载所有回扣、元数据和佣金。
我使用的HQL是:
Select store from Store as store;
我期望整个图表能够以尽可能少的 SQL 加载。为了防止 n+1 选择问题,我在 Store->Rebate 之间使用子选择获取。
但是,为了获取 RebateMetadata 和 RebateCommission,我看到多个单独的选择(带有连接)被触发。我应该怎样做才能最大程度地减少这种情况?
此外,我打开了二级缓存,但 QueryCache 关闭了。
I have the following structure
Store
Rebate
RebateMetadata
RebateCommission
So, the relation is like this -
Store -> Rebate is a one to many relation
Rebate -> RebateMetadata is a one-to-one mapping
Rebate -> RebateCommission is a one-to-one mapping
My Query is to load all stores. And with it, load all Rebates and metadatas and commissions.
The HQL I am using is:
Select store from Store as store;
I am expecting the whole graph to be loaded in as less SQLs as possible. To prevent the n+1 selects issue, I use subselect fetching between Store->Rebate.
However, to fetch RebateMetadata and RebateCommission, I see multiple individual selects(with joins) being fired. What should I do to minimize this?
Moreover, I have the 2nd level cache turned ON, but QueryCache turned OFF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试 获取连接。我通常需要一段时间才能弄好,尝试类似:
编辑:根据我在 hibernate 文档中链接的倒数第二个示例进行更新。这更有可能是正确的。
这可能行不通,但这是一般的想法。或者,您可以尝试在属性上使用批量大小(注释
@BatchSize
),以确保像这样的属性一次加载50个项目(使用SELECT ... IN查询) 。You could try a fetch join. It usually takes me a while to get it right, try something like:
edit: updated in accordance with the second to last example I linked in the hibernate docs. This has more of a chance of being correct.
That probably won't work but it's the general idea. Alternatively you could try using batch-size (annotation
@BatchSize
) on the property to make sure that properties like this are loaded, say, 50 items at a time (using a SELECT...IN query).