Home > Back-end >  Dynamic projection with Spring JPA repository and query DSL
Dynamic projection with Spring JPA repository and query DSL

Time:10-12

I currently have a Spring JPA Repository inheriting QuerydslPredicateExecutor and JpaRepository.

I'm using the Page<T> findAll(Predicate predicate, Pageable pageable) method from the QuerydslPredicateExecutor, but I would like to do a dynamic projection the same we can do it with JpaRepository (like <T> List<T> findByName(String name, Class<T> type) for example).

I tried to add a <T> Page<T> findAll(Predicate predicate, Pageable pageable, Class<T> type)

Is there a way to achieve this?

CodePudding user response:

Is there a way to achieve this?

Yes, there is.

Version 2.6 RC1 of Spring Data JPA introduced fluent APIs for Query By Example, Specifications, and Querydsl. This you can use among other things to configure projections. Note that only interface projections are supported.

You can use projections like this:

interface SomeRepository extends CrudRepository, QuerydslPredicateExecutor {}
MyService {

    @Autowired
    SomeRepository repository;

    void doSomething(){

        Page<ProjectionInterface> projections = 
            repository.findBy(
                querydslPredicate,
                q -> q.as(ProjectionInterface.class).page(pageRequest)
            );
        // ...
    }
}
  • Related