Jpa lazy fetching objects at multiple levels with api criteria

I use JPA2 with it criteria API to select my objects from the database. OpenJPA implementation on WebSphere Application Server. All my objects are modeled using Fetchtype = Lazy.

I select an object with some criteria from the database and I want to immediately download all the nested data from the sub-tables. If I have a datamodel where table A is connected to oneToMany with table B, I can use the 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); 

It works great. I get element A, and all of its elements B are filled correctly. Now table B has oneToMany related to table C, and I also want to load them. Therefore, I am adding the following query to my query:

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

But that will do nothing.

Does anyone know how to get layered objects in a single query?

+7
source share
1 answer

It does not work with JPQL, and there is no way to make it work in CriteriaQueries. The specification limits the received objects to those specified directly from the returned object:

Details on connecting fetch using CriteriaQuery:

The relationship or attribute referenced by the fetch method must be referenced from an object or inline that is returned as the result of the query.

About connecting fetch in JPQL:

The association referenced by the right side of the FETCH JOIN clause must be an association or collection item referenced by an object or nested that is returned as a result of the request.

The same limitation is also indicated in the OpenJPA documentation.

+10
source

All Articles