您是否应该在JPA中为每个表创建一个存储库? [英] Are you supposed to have one repository per table in JPA?
问题描述
你应该在JPA中为每个表创建一个存储库吗?如果没有,您如何解决存储库数据库中的泛型?
Are you supposed to have one repository per table in JPA? If not, how do you resolve the generics in the repository database?
例如,下面是 StoreRepository
。它处理 Store
对象上的 CRUD 操作。如果我希望存储库也保存 StoreEvent
对象,我将如何更改下面的接口以容纳这两个对象?
For example, below is a StoreRepository
. It handles CRUD operations on the Store
object. If I wanted the repository to save a StoreEvent
object as well, how would I go about changing the interface below to accommodate both objects?
@Repository
public interface StoreRepository extends JpaRepository<Store, String> {
public Store findByGuid(String guid);
}
推荐答案
由于存储库是一个派生概念从领域驱动设计,考虑数据库表是错误的方法。根据定义,您可以从存储库访问聚合根。实际上,存储库正在模拟这些集合。
As repository is a concept derived from Domain Driven Design, thinking about database tables is the wrong approach. By definition you access aggregate roots from a repository. Effectively a repository is simulating a collection of these.
现在形成聚合根的是什么?可能更有趣:什么不是?这当然在很大程度上取决于您的域名,但我在这里举个例子。包含 LineItems
的订单
通常被建模为聚合根。这是由于订单
的组合性质。如果没有周围的订单
, LineItem
将不存在。
Now what forms an aggregate root? Probably even more interesting: what does not? That's of course highly depending on your domain but let me give you an example here. An Order
containing LineItems
usually is modeled as an aggregate root. This is due to the composition nature of the Order
. A LineItem
would not exist without a surrounding Order
.
通常,持久性访问机制应遵循域原则。因此,您将订单
和 LineItem
建模为 @Entity
类但只创建一个 OrderRepository
,作为聚合根的形式,并有效地控制对象图中的一致性规则。
Usually the persistence access mechanisms should follow the domain principles. Thus, you'd model both Order
and LineItem
as @Entity
classes but only create an OrderRepository
, as the form the aggregate root and effectively control the consistency rules within the object graph.
我们强烈建议不使用商店特定的存储库基础接口,因为它们 - 顾名思义 - 公开商店细节(例如 flush()
)给可能不应该知道的客户端。请在我的回答中详细了解此处。
We also strongly recommend not to use the store specific repository base interfaces as they - as the name suggests - expose store specifics (e.g. flush()
) to the clients which the shouldn't be aware of if possible. Read more on that in my answer here.
这篇关于您是否应该在JPA中为每个表创建一个存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!