可以将多个存储库自动装配到 Spring Data JPA 中的另一个存储库吗?

Is it okay to Autowire multiple repositories into another repository in Spring Data JPA?

是否可以将多个存储库(JPA 接口)自动装配到另一个存储库(class),如下所示

@Repository
public class repositoryClass {
@Autowired
private Repository1 repo1;
@Autowired
private Repository2 repo2;
}

这里repository 1和2是SpringData JpaRepository接口

repositoryClass 的目的是从 repository1 和 repository2 获取 sql 查询,然后使用休眠执行它们,因此我将 repo1 和 repo2 自动装配到 repositoryClass

在一个 class 说主仓库中添加多个仓库是可以的。

@Repository
public class MasterRepository {
    @Autowired
    private Repository1 repo1;
    @Autowired
    private Repository2 repo2;
}

您将获得的好处是您无需在每个 classes 中添加您正在使用的每个存储库。您只需自动连接 masterrepository 并使用它。

来自 Microsoft 网站

The Repository pattern is a well-documented way of working with a data source. In the book Patterns of Enterprise Application Architecture, Martin Fowler describes a repository as follows:

A repository performs the tasks of an intermediary between the domain model layers and data mapping, acting in a similar way to a set of domain objects in memory. Client objects declaratively build queries and send them to the repositories for answers. Conceptually, a repository encapsulates a set of objects stored in the database and operations that can be performed on them, providing a way that is closer to the persistence layer. Repositories, also, support the purpose of separating, clearly and in one direction, the dependency between the work domain and the data allocation or mapping.

我认为最有趣的部分是最后一句话。设计模式(在本例中为 Repository Pattern)的作用是通过提供经过验证的解决方案使事情变得简单。按照您的代码所示进行操作,您违反了许多原则,例如 separation of concernssingle responsability principleinterface segregation

让事情尽可能简单。

这是糟糕的设计。除了打破 SOLID 的许多原则之外,这还导致非常高的耦合。让我们首先回顾一下存储库的用途:

The repository pattern is pretty simple. An interface defines the repository with all logical read and write operations for a specific entity (e.g User).

由此我们可以得出结论,存储库只有一个责任,即CRUD对特定实体的操作。然后,基于 SRP 原则,更改存储库实现的原因是映射实体发生更改时(例如,我们向用户添加了新列 table 并且我们想从数据库中获取它)或者我们想添加一些执行更多 CRUD 操作的新函数(在映射的实体上!)。

diagram1,如果你想改变repository4中的东西,你必须改变repository3repository2repository1,所以SRP原则被破坏了。这是一场建筑灾难。这是由于不同存储库之间的耦合度非常高。现在让我们考虑 图 2 中显示的其他设计。适配器用于使用多个存储库执行某些更复杂的操作,并将应用程序业务层与数据层分开。如果 repository4 中发生某些变化,我们将不得不更改 SomeAdapterB 但这不会影响业务逻辑,因为适配器是应用程序的一种网关.

总而言之,不要让存储库相互依赖。使用适配器。

PS 当您在 spring 中自动装配依赖项时使用构造函数注入!