简体   繁体   中英

Dynamic projection with Spring JPA repository and query DSL

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?

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)
            );
        // ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM