3.6.7.2. Custom Fetch Group Configuration
You can control the default set of fetch groups with the openjpa.FetchGroups configuration property.
Set this property to a comma-separated list of fetch group names.
You can also set the system’s default maximum fetch depth with the openjpa.MaxFetchDepth configuration property.
The maximum fetch depth determines how "deep" into the object graph to traverse when loading an instance.
For example, with a MaxFetchDepth of 1, OpenJPA will load at most the target instance and its immediate relations.
With a MaxFetchDepth of 2, OpenJPA may load the target instance, its immediate relations, and the relations of those relations.
This works to arbitrary depth.
In fact, the default MaxFetchDepth value is -1, which symbolizes infinite depth.
Under this setting, OpenJPA will fetch configured relations until it reaches the edges of the object graph.
Of course, which relation fields are loaded depends on whether the fields are eager or lazy, and on the active fetch groups.
A fetch group member’s recursion depth may also limit the fetch depth to something less than the configured maximum.
OpenJPA’s OpenJPAEntityManager and OpenJPAQuery extensions to the standard EntityManager and Query interfaces provide access to a
org.apache.openjpa.persistence.FetchPlan object.
The FetchPlan maintains the set of active fetch groups and the maximum fetch depth.
It begins with the groups and depth defined in the openjpa.FetchGroups and openjpa.MaxFetchDepth properties, but allows you to add or remove groups and change the maximum fetch depth for an individual EntityManager or Query through the methods below.
public FetchPlan addFetchGroup(String group);
public FetchPlan addFetchGroups(String... groups);
public FetchPlan addFetchGroups(Collection groups);
public FetchPlan removeFetchGrop(String group);
public FetchPlan removeFetchGroups(String... groups);
public FetchPlan removeFetchGroups(Collection groups);
public FetchPlan resetFetchGroups();
public Collection<String> getFetchGroups();
public void clearFetchGroups();
public FetchPlan setMaxFetchDepth(int depth);
public int getMaxFetchDepth();
Runtime Extensions details the OpenJPAEntityManager, OpenJPAQuery, and FetchPlan interfaces.
import org.apache.openjpa.persistence.*;
...
OpenJPAQuery kq = OpenJPAPersistence.cast(em.createQuery(...));
kq.getFetchPlan().setMaxFetchDepth(3).addFetchGroup("detail");
List results = kq.getResultList();