JPA:@OneToMany(fetch = FetchType.EAGER),分页和重复
JPA: @OneToMany(fetch = FetchType.EAGER), pagination and duplicates
我使用 eclipselink 作为 JPA 提供程序。我有一个实体文章,其中有很多作者(此字段标记为 @OneToMany(fetch = FetchType.EAGER)
)。文章和作者仅使用一个 sql 查询 (JOIN) 一起加载。
要使用分页,我使用以下代码:
String queryString="SELECT DISTINCT e FROM Article e LEFT JOIN FETCH e.authors";
Query query = em.createQuery(queryString);
query.setHint("eclipselink.join-fetch", "e.authors");
query.setFirstResult(position);
query.setMaxResults(amount);
据我所知,当使用 setFirstResult 和 setMaxResults 时,它们在 sql 查询中定义了 limit part
。结果我有两个问题:
- 当我想获取 10 篇文章时,我只获取了两篇文章,其中第一篇文章有 4 位作者,第二篇文章有 6 位作者
- 文章重复 - 我在不同页面上有一篇不同作者的文章。
如何解决这样的问题?
FirstResult 和 MaxResult 在对集合使用 fetch JOIN 时无法像您预期的那样工作,因为它们是数据库 SQL 性能操作,如所述 here。
如果您需要绝对分页结果,请不要在集合映射上使用提取连接 - 使用 batch fetching instead. This will use 2 queries, allowing the first to correctly return the required rows with pagination, and the second to return the rows required for the collection relationship. Specify the IN or batch.type 来限制辅助查询。
我使用 eclipselink 作为 JPA 提供程序。我有一个实体文章,其中有很多作者(此字段标记为 @OneToMany(fetch = FetchType.EAGER)
)。文章和作者仅使用一个 sql 查询 (JOIN) 一起加载。
要使用分页,我使用以下代码:
String queryString="SELECT DISTINCT e FROM Article e LEFT JOIN FETCH e.authors";
Query query = em.createQuery(queryString);
query.setHint("eclipselink.join-fetch", "e.authors");
query.setFirstResult(position);
query.setMaxResults(amount);
据我所知,当使用 setFirstResult 和 setMaxResults 时,它们在 sql 查询中定义了 limit part
。结果我有两个问题:
- 当我想获取 10 篇文章时,我只获取了两篇文章,其中第一篇文章有 4 位作者,第二篇文章有 6 位作者
- 文章重复 - 我在不同页面上有一篇不同作者的文章。
如何解决这样的问题?
FirstResult 和 MaxResult 在对集合使用 fetch JOIN 时无法像您预期的那样工作,因为它们是数据库 SQL 性能操作,如所述 here。
如果您需要绝对分页结果,请不要在集合映射上使用提取连接 - 使用 batch fetching instead. This will use 2 queries, allowing the first to correctly return the required rows with pagination, and the second to return the rows required for the collection relationship. Specify the IN or batch.type 来限制辅助查询。