如何使用QueryDslJpaRepository?

How to use QueryDslJpaRepository?

在我当前的项目设置中,我将存储库定义为:

public interface CustomerRepository extends JpaRepository<Customer, Long>, QueryDslPredicateExecutor<Customer> {
}

QueryDslPredicateExecutor 提供了额外的 findAll 方法,return 例如一个 Iterable。 它例如是否包含仅指定OrderSpecifier.

的方法

我刚刚遇到 QueryDslJpaRepository,它包含这些 PredicateOrderSpecifier 感知方法的更多变体,还有 return Lists 而不是Iterables.

我想知道为什么QueryDslPredicateExecutor是有限的,是否可以使用QueryDslJpaRepository方法?

我已经使用了自定义 BaseRepository,因此很容易确保我的存储库使用 List 变体(而不是 Iterable):

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {

    @Override
    List<T> findAll(Predicate predicate);

    @Override
    List<T> findAll(Predicate predicate, Sort sort);

    @Override
    List<T> findAll(Predicate predicate, OrderSpecifier<?>... orders);

    @Override
    List<T> findAll(OrderSpecifier<?>... orders);
}

请注意,我对 QueryDslPredicateExecutor 中缺少方法的评论是不正确的。

QueryDslJpaRepository 扩展了 SimpleJpaRepository

当你想adding custom behavior to all repositories时使用SimpleJpaRepository。这样做需要三个步骤:

第 1 步:创建一个扩展 JpaRepository 的接口(例如 CustomRepository),然后添加您自己的接口方法

第 2 步:创建一个实现您的 CustomRepository 的 class(例如 CustomRepositoryImpl),这自然需要您为定义在 CustomRepository 和 JpaRepository 以及 JpaRepository 中的每个方法提供具体的方法实现祖先接口。这将是一项乏味的工作,因此 Spring 提供一个具体的 SimpleJpaRepository class 来为您完成这项工作。所以你需要做的就是让 CustomRepositoryImpl 扩展 SimpleJpaRepository 然后只在你自己的 CustomRepository 接口中为该方法编写具体方法。

第 3 步:使 CustomRepositoryImpl 成为 jpa 配置中的新基础-class(在 xml 或 JavaConfig 中)

同样,QueryDslJpaRepository 是 SimpleJpaRepository 的直接替代品,当您的 CustomRepository 不仅扩展 JpaRepository 还扩展 QueryDslPredicateExecutor 接口时,为您的存储库添加 QueryDsl 支持。

我希望 Spring 数据 JPA 文档明确说明如果有人正在使用 QueryDslPredicateExecutor 但还想添加 his/her 自己的自定义方法时该怎么做。当应用程序抛出 "No property findAll found for type xxx" 或 "No property exists found for type xxx" 等错误时,我花了一些时间才弄清楚该怎么做。