jpa 使用标准 api 在多个级别上延迟获取实体 [英] jpa lazy fetch entities over multiple levels with criteria api

查看:20
本文介绍了jpa 使用标准 api 在多个级别上延迟获取实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA2 和它的 Criteria API 从数据库中选择我的实体.实现是 WebSphere Application Server 上的 OpenJPA.我所有的实体都是用 Fetchtype=Lazy 建模的.

I am using JPA2 with it's Criteria API to select my entities from the database. The implementation is OpenJPA on WebSphere Application Server. All my entities are modeled with Fetchtype=Lazy.

我从数据库中选择了一个具有某些条件的实体,并希望一次从子表中加载所有嵌套数据.如果我有一个数据模型,其中表 A 与表 B 连接为 oneToMany,我可以在条件查询中使用 Fetch 子句:

I select an entity with some criteria from the database and want to load all nested data from sub-tables at once. If I have a datamodel where table A is joined oneToMany to table B, I can use a Fetch-clause in my criteria query:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> root = cq.from(A.class);
Fetch<A,B> fetch = root.fetch(A_.elementsOfB, JoinType.LEFT);

这很好用.我得到一个元素 A 并且它的所有 B 元素都正确填充.现在表 B 与表 C 具有 oneToMany 关系,我也想加载它们.所以我将以下语句添加到我的查询中:

This works fine. I get an element A and all of its elements of B are filled correctly. Now table B has a oneToMany-relationship to table C and I want to load them too. So I add the following statement to my query:

Fetch<B,C> fetch2 = fetch.fetch(B_.elementsOfC, JoinType.LEFT);

但这不会有任何作用.

有人知道如何在一个查询中获取多级实体吗?

Does anybody know how to fetch multi level entities in one query?

推荐答案

它不适用于 JPQL,也无法使其在 CriteriaQueries 中运行.规范将获取的实体限制为直接从返回的实体引用的实体:

It does not work with JPQL and there is no way to make it work in CriteriaQueries either. Specification limits fetched entities to the ones in that are referenced directly from the returned entity:

关于使用 CriteriaQuery 获取连接:

About fetch join with CriteriaQuery:

fetch 方法引用的关联或属性必须是从作为结果返回的实体或可嵌入对象引用查询.

An association or attribute referenced by the fetch method must be referenced from an entity or embeddable that is returned as the result of the query.

关于 JPQL 中的 fetch join:

About fetch join in JPQL:

FETCH JOIN 子句右侧引用的关联必须是引用自的关联或元素集合作为查询结果返回的实体或可嵌入对象.

The association referenced by the right side of the FETCH JOIN clause must be an association or ele ment collection that is referenced from an entity or embeddable that is returned as a result of the query.

OpenJPA 文档中也提到了同样的限制.

Same limitation is also told in OpenJPA documentation.

这篇关于jpa 使用标准 api 在多个级别上延迟获取实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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