Spring Data JPA + JpaSpecificationExecutor + EntityGraph
Solution 1
The solution is to create a custom repository interface that implements these features:
@NoRepositoryBean
public interface CustomRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
List<T> findAll(Specification<T> spec, EntityGraphType entityGraphType, String entityGraphName);
Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraphType entityGraphType, String entityGraphName);
List<T> findAll(Specification<T> spec, Sort sort, EntityGraphType entityGraphType, String entityGraphName);
T findOne(Specification<T> spec, EntityGraphType entityGraphType, String entityGraphName);
}
Also create an implementation:
@NoRepositoryBean
public class CustomRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CustomRepository<T, ID> {
private EntityManager em;
public CustomRepositoryImpl(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
this.em = em;
}
@Override
public List<T> findAll(Specification<T> spec, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
TypedQuery<T> query = getQuery(spec, (Sort) null);
query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
return query.getResultList();
}
@Override
public Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
TypedQuery<T> query = getQuery(spec, pageable.getSort());
query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
return readPage(query, pageable, spec);
}
@Override
public List<T> findAll(Specification<T> spec, Sort sort, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
TypedQuery<T> query = getQuery(spec, sort);
query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
return query.getResultList();
}
@Override
public T findOne(Specification<T> spec, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
TypedQuery<T> query = getQuery(spec, (Sort) null);
query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
return query.getSingleResult();
}
}
And create a factory:
public class CustomRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new CustomRepositoryFactory(entityManager);
}
private static class CustomRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
private EntityManager entityManager;
public CustomRepositoryFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
protected Object getTargetRepository(RepositoryMetadata metadata) {
return new CustomRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
}
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
// The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
//to check for QueryDslJpaRepository's which is out of scope.
return CustomRepository.class;
}
}
}
And change the default repository factory bean to the new bean, e.g. in spring boot add this to the configuration:
@EnableJpaRepositories(
basePackages = {"your.package"},
repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class
)
For more info about custom repositories: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories
Solution 2
I managed to implement this with overriding of findAll
method and adding to it annotation @EntityGraph
:
public interface BookRepository extends JpaSpecificationExecutor<Book> {
@Override
@EntityGraph(attributePaths = {"book.author"})
List<Book> findAll(Specification<Book> spec);
}
Solution 3
The Joepie response is O.K.
but you don't need to create repositoryFactoryBeanClass, set up repositoryBaseClass
@EnableJpaRepositories(
basePackages = {"your.package"},
repositoryBaseClass = CustomRepositoryImpl.class)
Solution 4
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.
Solution 5
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:
The class needs to have a constructor of the super class which the store-specific repository factory implementation is using. In case the repository base class has multiple constructors, override the one taking an EntityInformation plus a store specific infrastructure object (e.g. an EntityManager or a template class).
I use the following constructor:
public CustomRepositoryImpl(JpaEntityInformation<T,?> entityInformation, EntityManager em) {
super(entityInformation, em);
this.domainClass = entityInformation.getJavaType();
this.em = em;
}
I've also added a private field to store the domain class:
private final Class<T> domainClass;
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:
@Override
public Page<T> findAll(Specification<T> spec, Pageable pageable, EntityGraph.EntityGraphType entityGraphType, String entityGraphName) {
TypedQuery<T> query = getQuery(spec, pageable.getSort());
query.setHint(entityGraphType.getKey(), em.getEntityGraph(entityGraphName));
return readPage(query, domainClass, pageable, spec);
}
Related videos on Youtube
Kerby
Updated on June 06, 2022Comments
-
Kerby almost 2 years
(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?
-
Rash almost 9 yearsDid you ever find the answer to this question?
-
-
Grant Lay almost 8 yearsGreat work @Joepie, saved me a couple of hours work.
-
Ortomala Lokni almost 6 years
readPage(javax.persistence.TypedQuery<T> query, Pageable pageable, @Nullable Specification<T> spec)
is now deprecated usereadPage(TypedQuery, Class, Pageable, Specification)
instead. -
Kruschenstein almost 4 yearsYou could simply use the SimpleJpaRepository
getDomainClass()
method instead (docs.spring.io/spring-data/jpa/docs/current/api/org/…) -
John Smith over 3 yearsVery elegant solution. Thanks :-)
-
leo over 3 years@vteraz I can't get this to work on the overridden
findById
of JpaRepository using a NamedEntityGraph declared on the Entity. What's the difference to the example above? Declaring a new methodfindWithAttributesAll
will respect the NamedEntityGraph. -
vteraz over 3 yearsit works for me even with the
@NamedEntityGraph
. Can you post an example of your case? -
Markus Pscheidt almost 3 yearsIn recent versions of Spring Data JPA (versions from
2.0
onwards), instead of(Sort) null
useSort.unsorted()
-
Raj almost 3 yearsIs there a way to use this solution for loading multiple OneToMany associations?