2

Is it possible to fetch all collections in an entity hierarchy eagerly in a particular query only?

For example,

entity Department has a list of entity Employee. Employee has a list of entity Address and a list of entity Credentials. Department has another list of entity Project.

I want to eagerly fetch all these collections (in my real case there are more collections) in a particular query SELECT dept FROM Department dept and not in other cases (so can't be annotated with FetchType.EAGER). Is it possible?

I am using Eclipselink.

Thanks in advance.

1
  • cant you have collection in Department Entity class like department.getEmployees() ?
    – vels4j
    Jan 3, 2013 at 10:15

3 Answers 3

7

You can use join fetching, batch fetching, or load groups.

I would recommend batch fetching over join fetching, as it will perform significantly better with multiple collections.

See,

http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html

Also, http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/q_batch.htm#batch

http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/q_join_fetch.htm#fetch

http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#Load_Examples

4

Nested fetch joins are not allowed by JPA, you should use the EclipseLink query hint eclipselink.join-fetch. See the answer to this question.

1

If I recall correctly, you need to use FETCH JOIN statements in your query.

See also: Fetch Joins

2
  • Doesn't it require me to FETCH JOIN each collection in the hierarchy?
    – Naveed S
    Jan 3, 2013 at 9:27
  • @NaveedS Not if you build your query dynamically to include the fetch only when you need it. Jan 3, 2013 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.