我对 DDD 很陌生,我正在尝试正确实现我的用例。
我有多个实体,它们都捆绑在一起,很像通常Order封装LineItem.
根据我对基本 DDD 的理解,我倾向于创建 2 个实体,一个用于订单,另一个用于行项目,但似乎有 2 个选项:
让两个存储库返回Tx,将它们全部实例化到另一个接口/结构中作为“聚合”(可能不是正确的名称)以使交易创建新订单
创建一个新的存储库,然后该存储库将在订单的整个范围内自行执行事务(创建订单+行项目)
对我来说,第二个选项似乎比第一个选项更容易实现。我可以进行连接、交易或此存储库中所需的任何内容,以从两个表(订单和行项目)检索数据,还可以创建事务并确保其数据完整性。但我不确定这是否是一个好的做法。
“伪代码”看起来像这样:
type Order struct {
ID int
lineItems []LineItem
...
}
type LineItem struct {
ID int
...
}
type OrderRepoistory interface {
GetOrders()([]*Order,err)
GetOrder(id int)(*Order,err)
Create(order *Order) err
}
Run Code Online (Sandbox Code Playgroud)
在OrderRepository实现内部,创建函数看起来像这样:
func Create(order *Order) err {
tx := BeginTX
insert order into the orders table
insert the lineitems into the line_items table
tx.commit or rollback
return nil or …Run Code Online (Sandbox Code Playgroud)