简体   繁体   English

使用 Spring JPA 存储库和查询 DSL 的动态投影

[英]Dynamic projection with Spring JPA repository and query DSL

I currently have a Spring JPA Repository inheriting QuerydslPredicateExecutor and JpaRepository .我目前有一个 Spring JPA 存储库继承QuerydslPredicateExecutorJpaRepository

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).我正在使用 QuerydslPredicateExecutor 中的Page<T> findAll(Predicate predicate, Pageable pageable) QuerydslPredicateExecutor ) 方法,但我想做一个动态投影,就像我们可以用JpaRepository做的一样(比如<T> List<T> findByName(String name, Class<T> type)例如)。

I tried to add a <T> Page<T> findAll(Predicate predicate, Pageable pageable, Class<T> type)我试图添加一个<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. Spring 数据 JPA 的 2.6 RC1 版本引入了用于按示例查询、规范和 Querydsl 的流畅 API。 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)
            );
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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