是否可以创建一个通用存储库来扩展扩展 Spring 的 CrudRepository 的其他接口?

Is it possible to create a generic repository that extends other interfaces that extend Spring's CrudRepository?

详情如下:

我的应用程序中有多个模型,每个模型都有一个扩展 Spring 的 CrudRepository.

的存储库

例如:

我想创建一个通用的 MyApplicationRepository 来扩展我所有的个人存储库,这样我只需要创建一个 MyApplicationRepository 实例,而不是创建我个人存储库的多个实例。

我试过这个:

public interface MyApplicationRepositoryInterface extends
    EyeColorRepository,
    HairColorRepository,
    StateRepository {
}


public class MyApplicationRepository implements MyApplicationRepositoryInterface {
}

但是,当我尝试扩展 MyApplicationRepositoryInterface 中的所有个人存储库时,出现此错误:

CrudRepository cannot be inherited with different arguments: <com.myapp.Models.EyeColor, java.lang.Long> and <com.myapp.Models.HairColor, java.lang.Long>

那么有没有办法做我想做的事情,或者我是否坚持实例化我所有模型存储库的实例?

这是错误的做法。不应实施 CrudRepositories。 您只需通过扩展 CrudRepository 接口为所有模型创建存储库接口。 Spring 在运行时提供实现。

如果您想通过单个 class 访问这些,则创建一个服务 class,其方法可以访问这些单独存储库中所需的方法。

首先,我将尝试解释您遇到的错误:CrudRepository 是一个参数化接口,并且继承自(多个)CrudRepository 不同参数化类型的接口会产生冲突在运行时。

IMO,你想做的事适得其反。当您扩展 CrudRepository 时,Spring 的数据存储库在运行时提供类型安全的 CRUD 方法实现。这为您提供了更清晰的代码,并提供了编译时的正确性。而且,CrudRepository 已经很通用了——这样更好(在接口级别,而不是在实现级别)。

即使您要创建这样的存储库,您也必须放弃使用 CrudRepository 并创建一个包含所有模型(例如,保存眼睛颜色、保存头发颜色等)。也许使用 SpringTemplate 之类的东西。这不是 IMO 的最佳方式,因为您将混合域对象并且 class 将成为维护的噩梦。

要回答您的问题,是的,您必须为每个模型注入一个单独的存储库实例。

如果您正在寻找 运行 自定义 SQL 查询 spring boot with repository structures。请看一下