Search code examples
jpajpa-2.0eclipselinkjpql

Fetch all collections eagerly in JPA


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.


Solution

  • 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