gpt4 book ai didi

java - 渴望使用 ScrollableResults 在 Hibernate 中获取集合

转载 作者:搜寻专家 更新时间:2023-11-01 00:52:12 25 4
gpt4 key购买 nike

我正在尝试使用 Hibernate 从表中检索大约 1 亿行。我有一个持久实体项目,其中包含内部的费用集合(另一个持久实体)。鉴于我遍历结果并访问每个对象的费用,我想急切地获取费用以避免 n+1 问题。

我还应该提到我想将它连接到另一个名为 Provider 的表(一对一映射但没有外键)。我试过:

String query = "select new " + Order.class.getName() 
+ "(i, p) from Item i left join fetch i.fees f, Provider p where "
+ "p.factoryId=i.factoryId and p.factoryRef=i.factoryRef";

return session.createQuery(query).scroll();

我的 Order 类包含一个 Provider 字段和一个 Item 字段。我收到此错误:

Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list

我想以一个可滚动的订单列表结束,其中包含项目(急切收取的费用)和提供商。

最佳答案

SelectClause 中的这段代码会给您带来麻烦:

if ( !fromElementsForLoad.contains( origin ) ) {
throw new QueryException(
"query specified join fetching, but the owner " +
"of the fetched association was not present in the select list " +
"[" + fromElement.getDisplayText() + "]"
);

如您所见,当提到 fetch 关键字时,hibernate 会检查您是否请求 fetch 装饰字段 parent。 fromElementsForLoad.contains(原点)

他们这样做可能是为了防止您进行冗余连接,这会降低您的性能。这是一件好事,因为如果您从不使用它,就没有理由获取它。

我相信在你的情况下 - 在新的 Order.class 中包装 Item.class 隐藏了你在查询中使用 fetch 装饰字段 parent 的事实.

我目前没有调试能力,所以我无法验证这一点。尝试调试 SelectClause.class 中的这一行并查看 fromElementsForLoad 集合包含哪些元素。

如果您想避免 n+1 问题,我建议在查询后初始化 Order.class。您只能选择项目和提供者。

如果您无法验证这一点,我将在下周找到合适的计算机并扩展我的答案。

关于java - 渴望使用 ScrollableResults 在 Hibernate 中获取集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com