对于最新的稳定版本,请使用 Spring Data Cassandra 5.0.4spring-doc.cadn.net.cn

自定义仓库实现

Spring Data 提供了多种选项,只需少量编码即可创建查询方法。 但当这些选项无法满足您的需求时,您也可以为仓库方法提供自己的自定义实现。 本节将介绍如何实现这一点。spring-doc.cadn.net.cn

自定义单个仓库

要为仓库(repository)添加自定义功能,首先必须定义一个片段接口以及该自定义功能的实现,如下所示:spring-doc.cadn.net.cn

自定义仓库功能的接口
interface CustomizedUserRepository {
  void someCustomMethod(User user);
}
自定义仓库功能的实现
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  @Override
  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

与片段接口对应的类名中,最重要的部分是 Impl 后缀。 你可以通过设置 @Enable<StoreModule>Repositories(repositoryImplementationPostfix = …) 来自定义特定于存储的后缀。spring-doc.cadn.net.cn

历史上,Spring Data 自定义仓库实现的发现遵循一种命名模式,该模式从仓库派生出自定义实现类的名称,从而实际上只允许一个自定义实现。spring-doc.cadn.net.cn

位于与仓库接口相同包中的类型,其名称与仓库接口名称加上实现后缀相匹配, 将被视为自定义实现,并作为自定义实现进行处理。 遵循该命名规则的类可能会导致非预期的行为。spring-doc.cadn.net.cn

我们认为单一自定义实现的命名方式已过时,建议不要使用此模式。 请改用基于片段(fragment-based)的编程模型。spring-doc.cadn.net.cn

该实现本身不依赖于 Spring Data,可以是一个普通的 Spring Bean。 因此,您可以使用标准的依赖注入行为来注入对其他 Bean(例如 JdbcTemplate)的引用、参与切面(aspects)等。spring-doc.cadn.net.cn

然后,您可以让你的仓库接口继承该片段接口,如下所示:spring-doc.cadn.net.cn

对您的仓库接口的更改
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}

通过您的仓库接口扩展片段接口,可以将 CRUD 功能与自定义功能结合起来,并使其对客户端可用。spring-doc.cadn.net.cn

Spring Data 仓库通过使用组成仓库组合的片段来实现。 这些片段包括基础仓库、功能切面(例如 Querydsl),以及自定义接口及其对应的实现。 每次向仓库接口中添加一个接口时,都会通过增加一个片段来增强该组合。 基础仓库和仓库切面的实现由各个 Spring Data 模块提供。spring-doc.cadn.net.cn

以下示例展示了自定义接口及其实现:spring-doc.cadn.net.cn

带有其实现的片段
interface HumanRepository {
  void someHumanMethod(User user);
}

class HumanRepositoryImpl implements HumanRepository {

  @Override
  public void someHumanMethod(User user) {
    // Your custom implementation
  }
}

interface ContactRepository {

  void someContactMethod(User user);

  User anotherContactMethod(User user);
}

class ContactRepositoryImpl implements ContactRepository {

  @Override
  public void someContactMethod(User user) {
    // Your custom implementation
  }

  @Override
  public User anotherContactMethod(User user) {
    // Your custom implementation
  }
}

以下示例展示了扩展 CrudRepository 的自定义仓库接口:spring-doc.cadn.net.cn

对您的仓库接口的更改
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

  // Declare query methods here
}

仓库可以由多个自定义实现组成,这些实现会按照其声明的顺序被导入。 自定义实现的优先级高于基础实现和仓库切面(aspects)。 这种排序机制允许你覆盖基础仓库和切面中的方法,并在两个片段提供相同方法签名时解决歧义。 仓库片段不仅限于在单一仓库接口中使用。 多个仓库可以共用同一个片段接口,从而让你在不同的仓库之间复用自定义逻辑。spring-doc.cadn.net.cn

以下示例展示了一个仓库片段及其实现:spring-doc.cadn.net.cn

覆盖 save(…) 的片段
interface CustomizedSave<T> {
  <S extends T> S save(S entity);
}

class CustomizedSaveImpl<T> implements CustomizedSave<T> {

  @Override
  public <S extends T> S save(S entity) {
    // Your custom implementation
  }
}

以下示例展示了一个使用前述仓库片段的仓库:spring-doc.cadn.net.cn

自定义仓库接口
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}

配置

仓库基础设施会尝试通过扫描发现仓库所在包下的类,以自动检测自定义实现片段。 这些类需要遵循命名约定,即在名称后附加一个默认为 Impl 的后缀。spring-doc.cadn.net.cn

以下示例展示了一个使用默认后缀的仓库,以及一个为后缀设置自定义值的仓库:spring-doc.cadn.net.cn

示例 1. 配置示例
@EnableCassandraRepositories(repositoryImplementationPostfix = "MyPostfix")
class Configuration { … }
<repositories base-package="com.acme.repository" />

<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />

前面示例中的第一个配置尝试查找名为 com.acme.repository.CustomizedUserRepositoryImpl 的类,用作自定义仓库实现。 第二个示例尝试查找 com.acme.repository.CustomizedUserRepositoryMyPostfixspring-doc.cadn.net.cn

歧义解析

如果在不同包中找到多个具有匹配类名的实现,Spring Data 会使用 Bean 名称来确定使用哪一个。spring-doc.cadn.net.cn

鉴于前面所示的 CustomizedUserRepository 的以下两种自定义实现,将使用第一种实现。 其 Bean 名称为 customizedUserRepositoryImpl,该名称与片段接口(CustomizedUserRepository)的名称加上后缀 Impl 相匹配。spring-doc.cadn.net.cn

示例 2. 模糊实现的解析
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}

如果你使用 UserRepository 注解 @Component("specialCustom") 接口,那么该 Bean 的名称加上 Impl 后,就会与在 com.acme.impl.two 中为仓库实现所定义的名称相匹配,并会替代第一个实现被使用。spring-doc.cadn.net.cn

手动配置

如果你的自定义实现仅使用基于注解的配置和自动装配,那么前面所示的方法可以很好地工作,因为该实现会被视为与其他任何 Spring Bean 一样。 如果你的实现片段 Bean 需要特殊的装配方式,你可以按照前一节中描述的约定来声明该 Bean 并为其命名。 这样,基础设施将通过名称引用手动定义的 Bean 定义,而不是自行创建一个。 以下示例展示了如何手动装配一个自定义实现:spring-doc.cadn.net.cn

示例3. 自定义实现的手动装配
class MyClass {
  MyClass(@Qualifier("userRepositoryImpl") UserRepository userRepository) {
    …
  }
}
<repositories base-package="com.acme.repository" />

<beans:bean id="userRepositoryImpl" class="…">
  <!-- further configuration -->
</beans:bean>

使用 spring.factories 注册片段

正如配置部分中已经提到的,基础设施仅会自动检测仓库基础包(base-package)内的片段(fragments)。 因此,如果位于其他位置的片段或由外部归档文件提供的片段与仓库不共享同一个命名空间,则不会被发现。 如以下部分所述,在 spring.factories 中注册这些片段可以绕过此限制。spring-doc.cadn.net.cn

假设您希望为您的组织提供一些自定义的搜索功能,这些功能可跨多个仓库使用,并利用文本搜索索引。spring-doc.cadn.net.cn

首先,你需要的是片段接口。 注意泛型 <T> 参数,用于将片段与仓库的领域类型对齐。spring-doc.cadn.net.cn

片段接口
public interface SearchExtension<T> {

    List<T> search(String text, Limit limit);
}

假设实际的全文搜索功能通过一个 SearchService 提供,该服务已在上下文中注册为一个 Bean,因此你可以在我们的 SearchExtension 实现中使用它。 运行搜索所需的一切只是一个集合(或索引)名称,以及一个将搜索结果转换为实际领域对象的对象映射器,如下所示。spring-doc.cadn.net.cn

片段实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T> {

    private final SearchService service;

    DefaultSearchExtension(SearchService service) {
        this.service = service;
    }

    @Override
    public List<T> search(String text, Limit limit) {
        return search(RepositoryMethodContext.getContext(), text, limit);
    }

    List<T> search(RepositoryMethodContext metadata, String text, Limit limit) {

        Class<T> domainType = metadata.getRepository().getDomainType();

        String indexName = domainType.getSimpleName().toLowerCase();
        List<String> jsonResult = service.search(indexName, text, 0, limit.max());

        return jsonResult.stream().map(…).collect(toList());
    }
}

在上面的示例中,使用 RepositoryMethodContext.getContext() 来获取实际方法调用的元数据。 RepositoryMethodContext 提供了附加到仓库的信息,例如领域类型(domain type)。 在此情况下,我们使用仓库的领域类型来确定要搜索的索引名称。spring-doc.cadn.net.cn

暴露调用元数据是有代价的,因此默认情况下它是禁用的。 要访问 RepositoryMethodContext.getContext(),您需要对负责创建实际仓库的仓库工厂进行增强,以暴露方法元数据。spring-doc.cadn.net.cn

公开仓库元数据

向片段实现中添加 RepositoryMetadataAccess 标记接口将触发基础设施,并为使用该片段的仓库启用元数据暴露功能。spring-doc.cadn.net.cn

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.support.RepositoryMetadataAccess;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T>, RepositoryMetadataAccess {

    // ...
}

可以通过 exposeMetadata 直接在仓库工厂 Bean 上设置 BeanPostProcessor 标志。spring-doc.cadn.net.cn

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;
import org.springframework.lang.Nullable;

@Configuration
class MyConfiguration {

    @Bean
    static BeanPostProcessor exposeMethodMetadata() {

        return new BeanPostProcessor() {

            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) {

                if(bean instanceof RepositoryFactoryBeanSupport<?,?,?> factoryBean) {
                    factoryBean.setExposeMetadata(true);
                }
                return bean;
            }
        };
    }
}

请不要仅仅复制/粘贴上述代码,而应结合您的实际使用场景进行考虑,因为上述做法会在每个仓库上简单地启用该标志,而您的场景可能需要一种更细粒度的方法。spring-doc.cadn.net.cn

在同时具备片段声明和实现之后,您可以在 META-INF/spring.factories 文件中注册该扩展,并在需要时打包相关内容。spring-doc.cadn.net.cn

META-INF/spring.factories 中注册该片段
com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension

现在你已经可以使用你的扩展了;只需将该接口添加到你的仓库中即可。spring-doc.cadn.net.cn

使用它
import com.acme.search.SearchExtension;
import org.springframework.data.repository.CrudRepository;

interface MovieRepository extends CrudRepository<Movie, String>, SearchExtension<Movie> {

}

自定义基础仓库

上一节中描述的方法要求在你希望自定义基础仓库行为(从而影响所有仓库)时,对每个仓库接口进行定制。 要改为对所有仓库统一更改行为,你可以创建一个实现类,该类继承特定于持久化技术的仓库基类。 然后,该类将作为仓库代理的自定义基类,如下例所示:spring-doc.cadn.net.cn

自定义仓库基类
class MyRepositoryImpl<T, ID>
  extends SimpleJpaRepository<T, ID> {

  private final EntityManager entityManager;

  MyRepositoryImpl(JpaEntityInformation entityInformation,
                          EntityManager entityManager) {
    super(entityInformation, entityManager);

    // Keep the EntityManager around to used from the newly introduced methods.
    this.entityManager = entityManager;
  }

  @Override
  @Transactional
  public <S extends T> S save(S entity) {
    // implementation goes here
  }
}
该类需要具有一个超类的构造函数,供特定于存储的仓库工厂实现使用。 如果仓库基类有多个构造函数,请重写接受 EntityInformation 以及特定于存储的基础设施对象(例如 EntityManager 或模板类)的那个构造函数。

最后一步是让 Spring Data 基础设施感知到自定义的仓库基类。 在配置中,你可以通过使用 repositoryBaseClass 来实现,如下例所示:spring-doc.cadn.net.cn

示例4. 配置自定义仓库基类
@Configuration
@EnableCassandraRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
     base-class="….MyRepositoryImpl" />