(Using Spring Data JPA) I have two entities Parent
& Child
with a OneToMany/ManyToOne bi-directional relationship between them. I add a @NamedEntityGraph
to the parent entity like so:
@Entity
@NamedEntityGraph(name = "Parent.Offspring", attributeNodes = @NamedAttributeNodes("children"))
public class Parent{
//blah blah blah
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
Set<Child> children;
//blah blah blah
}
Notice that the fetch type for the Parent's children is LAZY. This is on purpose. I don't always want to eager load the children when I'm querying an individual parent. Normally I could use my named entity graph to eager load the children on-demand, so to speak. But.....
There is a specific situation where I'd like to query for one or more parents AND eager load their children. In addition to this I need to be able to build this query programmatically. Spring Data provides the JpaSpecificationExecutor which allows one to build dynamic queries, but I can't figure out how to use it in conjunction with entity graphs for eager loading children in this specific case. Is this even possible? Is there some other way to eager load 'toMany entities using specifications?
Project Spring Data JPA EntityGraph implements some of the approaches mentioned in the other answers.
It has for example these additional repository interfaces:
EntityGraphJpaRepository
which is equivalent to standardJpaRepository
EntityGraphJpaSpecificationExecutor
which is equivalent to standardJpaSpecificationExecutor
Check the reference documentation for some examples.
The solution is to create a custom repository interface that implements these features:
Also create an implementation:
And create a factory:
And change the default repository factory bean to the new bean, e.g. in spring boot add this to the configuration:
For more info about custom repositories: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories
To complement the answers of Joep and pbo, I have to say that with new versions of Spring Data JPA, you will have to modify the constructor of
CustomRepositoryImpl
. Now the documentation says:I use the following constructor:
I've also added a private field to store the domain class:
This allow me to get rid of the deprecated method
readPage(javax.persistence.TypedQuery<T> query, Pageable pageable, @Nullable Specification<T> spec)
and use instead:The Joepie response is O.K.
but you don't need to create repositoryFactoryBeanClass, set up repositoryBaseClass