javaspring-data-jpaquerydsldtoentitygraph

Spring Data: Query DTOs with QueryDSL predicates


I am using QueryDSL to query/filter entities (Document):

   public interface DocumentRepository extends PagingAndSortingRepository<Document, Long>, QueryDslPredicateExecutor<Document>

Then I build QueryDSL Predicates and use method findAll to filter results:

   Predicate predicate = myBuilder.buildPredicate(myUserFilterObject)
   Page<Document> page = documentRepository.findAll(predicate, pageable)

It works well except for that I need to avoid N+1 selects (JPA). Is there any way to query DTOs instead of entities (but still use QueryDSL predicates) or is it possible to apply EntityGraphs here (didn't work for me)?


Solution

  • From Spring Data JPA 2.1 onwards you can use @EntityGraph annotation.

    public interface DocumentRepository extends PagingAndSortingRepository<Document, Long>, QueryDslPredicateExecutor<Document> {
        @EntityGraph(attributePaths = { "name_of_collection_to_load" })
        Page<Document> findAll(com.querydsl.core.types.Predicate predicate, Pageable pageable)
    }