1

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)?

miran
  • 1,419
  • 1
  • 12
  • 26

1 Answers1

1

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)
}
shazin
  • 21,379
  • 3
  • 54
  • 71
  • Ok, it works *somehow*, but it doesn't solve OneToOne relations (in multiple layers) - it still adds additional select - if I use EntityGraph to force loading of OneToOne object (let's call it directOneToOneChild) in main query, it works, but if this onedirectOneToOneChild has another OneToOne relationship, there are still additional N selects. – miran Nov 29 '17 at 14:15
  • Ok, I missed NamedAttributeNode/subgraphs, it works then. – miran Dec 05 '17 at 15:07