除了实现基础的仓库接口之外,也可以使用注解,不实现任何仓库接口。

使用 @NoRepositoryBean 注解,然后可以选择性地暴露 CRUD 方法:

@NoRepositoryBean
interface MyBaseRepository<T, ID> extends Repository<T, ID> {

  Optional<T> findById(ID id);

  <S extends T> S save(S entity);
}

interface UserRepository extends MyBaseRepository<User, Long> {
  User findByEmailAddress(EmailAddress emailAddress);
}

这些方法会被路由到 SimpleXxxRepository 上。

多 Spring Data 模块解决冲突

例如同时在项目中使用 Spring Data Redis 和 Spring Data MongoDB,也就是说使用了不同的持久化技术。这个时候 Repository 的定义必须区分持久化技术:

  1. Repository 继承了特定持久化技术的接口,此时使用该持久化技术
  2. 实体类被标注了特定持久化技术的注解(例如 MongoDB 使用的 @Document),此时使用对应的持久化技术。不要使用不同模块的注解
  3. 通过 @EnableXXXRepositories(basePackages = …) 明确指定扫描路径