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



我目前有一个继承QuerydslPredicateExecutorJpaRepository的Spring JPA存储库。

我使用的是QuerydslPredicateExecutor中的Page<T> findAll(Predicate predicate, Pageable pageable)方法,但我想做一个动态投影,就像我们用JpaRepository做的一样(比如<T> List<T> findByName(String name, Class<T> type)(。

我尝试添加<T> Page<T> findAll(Predicate predicate, Pageable pageable, Class<T> type)

有办法做到这一点吗?

有办法做到这一点吗?

是的,有.

SpringDataJPA的2.6RC1版本为QueryByExample、Specification和Querydsl引入了流畅的API。除其他外,您还可以使用它来配置投影。请注意,仅支持界面投影。

你可以使用这样的投影:

interface SomeRepository extends CrudRepository, QuerydslPredicateExecutor {}
MyService {
@Autowired
SomeRepository repository;
void doSomething(){
Page<ProjectionInterface> projections = 
repository.findBy(
querydslPredicate,
q -> q.as(ProjectionInterface.class).page(pageRequest)
);
// ...
}
}

最新更新