Search code examples
spring-bootjpaspring-data-jpaentitygraph

Can we make Spring JPA Specifications work with EntityGraph?


I am implementing a dynamic query logic using JPA specifications on an entity. The entity is having multiple relations with other entities. I am running into the issue of generating too many queries while executing JPA specifications.

Is there a way to combine JPA specifications findAll(specification, page) with EntityGraph so that we can one query generated while executing the same?


Solution

  • Yes it is absolutely possible to pass EntityGraph using EntityGraphJpaSpecificationExecutor

    @Repository
    public interface UserRepository
            extends JpaRepository<EntityClassName, DatatypeOfPrimaryKey>, EntityGraphJpaSpecificationExecutor<EntityClassName> {
    }
    
    userRepository.findAll(specification, pageable, new NamedEntityGraph(EntityGraphType.FETCH, "graphName"))