DDD 電商架構實戰!
大家好,我是 Tom 哥。
DDD 着重於將業務領域中的概念和對象映射到對象中,使對象模型能夠更好地反映業務的真實情況,從而使設計更具可理解性和可維護性。
今天,跟大家聊聊 DDD 在電商系統架構上的一些實戰經驗
1. 面向對象設計是 DDD 的核心
DDD 是一種領域驅動的設計方法,旨在通過建立對領域模型的清晰理解來解決業務問題。和事務腳本不同,DDD 使用面向對象設計來應對複雜的業務場景。
簡單來說,DDD 是由領域對象承載業務邏輯,所有的業務操作均在模型對象上完成,同一對象上不同的業務操作構成了對象的生命週期。
我們以訂單爲例,如下圖所示:
-
首先,用戶操作下單,使用提交數據爲其創建一個 Order 對象,版本 V1;
-
隨後,用戶進行改地址操作,調用 Order 對象的 modifyAddress 方法,Order 從原來的 V1 變成 V2;
-
用戶完成支付後,調用 Order 對象的 paySuccess 方法,Order 從 V2 變成 V3;
從圖上可見,在 DDD 設計中,所有的業務邏輯均由業務對象完成,所以面向對象是 DDD 設計的核心。
2. 爲什麼需要 Repository?
假設,有一臺非常牛逼的計算機,計算資源無限、內存大小無限、永不掉電、永不宕機,那最簡單高效的方式便是將模型對象全部放在內存中。
但,現實不存在這樣的機器,我們不得不將內存對象寫入磁盤,下次使用時,在將其從磁盤讀入到內存。
整體結構如下圖所示:
和上圖相比,具有如下特點:
-
業務操作沒變,仍舊依次完成 下單、改地址、支付等操作
-
引入持久化存儲(MySQL),可以將 Order 對象存儲於關係數據庫
-
配合 Order 的生命週期,操作中增加 save、load 和 update 等操作
-
用戶下單創建 Order 對象,通過 save 方法將 Order 對象持久化到 DB
-
接收到業務操作,需執行 load,從 DB 加載數據到內存 並對 Order 對象的狀態進行恢復
-
在業務操作完成後,需執行 update,將 Order 對象的最新狀態同步的 DB
相對全內存版本確實增加了不小的複雜性,爲了更好的對這些複雜性進行管理,引入 Repository 模式。
在領域驅動設計(DDD)中,Repository 是一種設計模式,它是用來存儲領域對象的容器。它提供了一種統一的方式來查詢和存儲領域對象。Repository 提供了對底層數據存儲的抽象,允許應用程序在沒有直接與數據存儲技術交互的情況下訪問數據,同時該抽象允許在不修改應用程序代碼的情況下更改數據存儲技術。
3. 什麼纔是好的 Repository ?
好的 Repository 應該在滿足業務需求的前提下,具備以下特性:
-
高內聚:好的 Repository 應該滿足單一職責原則,每個 Repository 只關注一種領域對象的存儲;
-
松耦合:好的 Repository 應該通過抽象接口與其他層進行交互,保證它們之間的耦合度低;
-
簡單易用:好的 Repository 應該提供一組易於使用的方法,方便開發人員使用;
-
可維護性:好的 Repository 應該易於維護,維護人員不需要長時間閱讀代碼才能瞭解它的工作原理;
說的太官方了,用人話就是:
-
需要一個統一的 Repository 接口,用於對易用方法 save、load、update 進行管理
-
爲每個聚合根創建一個 Repository 接口,繼承自 統一 Repository,只關注該聚合根的存儲
-
Repository 的實現儘可能的簡單,最好不用實現(人都是懶的)
4. 初始 Spring Data
Spring Data 是一個框架,旨在簡化數據訪問層的開發。它通過抽象和模板化方法,使得與各種數據存儲(如關係型數據庫,文檔數據庫,圖形數據庫,緩存等)的交互變得更加簡單和標準化。
Spring Data 通過提供簡單的、通用的數據訪問接口(如 Repository)和自動生成實現代碼,使得開發人員不必編寫重複的數據訪問代碼。這樣,開發人員可以專注於業務邏輯,而無需關注數據存儲和訪問的細節。
總的來說,Spring Data 的主要解決的問題是:簡化數據訪問層的開發,提高代碼複用性,降低開發複雜度。
Spring Data 對多種數據存儲提供了支持,本文以 Spring Data Jpa 爲例,快速實現應用程序與關係數據庫的交互。
4.1. 引入 Spring Data Jpa
Spring Data JPA 是 Spring Data 家族的重要成員,主要解決 Java 應用程序使用 JPA 完成對數據庫的訪問問題。它提供了一種簡單而靈活的方法來訪問和管理數據,並且可以消除重複代碼和提高開發效率。
首先,需要在 pom 中 引入 spring-data-jpa-starter,具體如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
其次,引入 MySQL 驅動,具體如下:
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Spring Data Jpa 默認實現是 Hibernate,而 Hibernate 是目前最流行且功能最強大的 JPA 實現,它提供了強大的映射、查詢和事務管理能力。
4.2. 完成配置
在 application.yml 增加 DB 和 Jpa 相關配置,具體如下:
spring:
application:
name: Spring-Data-for-DDD-demo
datasource:
# 數據庫配置信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/books
username: root
password: root
jpa:
# 打印 sql
show-sql: true
在啓動類上啓用 Spring Data Jpa。
@SpringBootApplication
// 開啓 Spring Data Jpa, basePackages 是 Repository 接口存放的包路徑
@EnableJpaRepositories(basePackages = "com.geekhalo.springdata4ddd.order.repository")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.3. 使用 Repository
一切就緒,接下來就可以爲模型創建專屬 Repository,具體如下:
public interface OrderCommandRepository extends JpaRepository<Order, Long> {
}
至此,Order 的專屬 Repository 就開發完成。
不知道你是否存在疑問:
-
說好的統一的易用方法在哪裏?
-
爲什麼沒有看到實現代碼?
一般情況下,JpaRepository 接口中的方法就能滿足大部分需求,典型方法包括:
5. 實戰 -- 訂單
爲了體現 Spring Data Jpa 的強大功能,以最常見的訂單爲例,業務模型如下圖所示:
-
一筆下單對應一個訂單(Order)
-
一個訂單可以有一個收穫地址(OrderAddress)
-
一個訂單可以關聯多個訂單項(OrderItem)
對應到領域模型如下:
核心代碼如下:
@Data
@Entity
@Table(name = "tb_order")
@Setter(AccessLevel.PRIVATE)
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "status")
@Enumerated(EnumType.STRING)
private OrderStatus status;
@Column(name = "price")
private int price;
// 收貨地址
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "user_address_id")
private OrderAddress address;
// 訂單項
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "order_id")
private List<OrderItem> items = new ArrayList<>();
}
5.1. 生單
先簡單看下生單的核心代碼,具體如下:
@Transactional(readOnly = false)
public Order createOrder(CreateOrderCommand command){
// 創建內存對象
Order order = Order.create(command);
// 保存到數據庫
this.repository.save(order);
return order;
}
// Order 實體上的 create 方法
public static Order create(CreateOrderCommand command) {
// 創建內存對象
Order order = new Order();
order.setUserId(command.getUserId());
String userAddress = command.getUserAddress();
if (!StringUtils.hasText(userAddress)){
// 設置收穫地址
OrderAddress orderAddress = new OrderAddress();
orderAddress.setDetail(userAddress);
order.setAddress(orderAddress);
}
// 添加訂單項
List<ProductForBuy> productForBuys = command.getProducts();
productForBuys.stream()
.map(productForBuy -> OrderItem.create(productForBuy))
.forEach(orderItem -> order.addOrderItem(orderItem));
order.init();
return order;
}
單元測試,具體如下:
@Test
void createOrder() {
// 創訂單,將整個 Order 聚合根全部保存到數據庫,包括
// 1. order
// 2. orderItem
// 3. orderAddress
CreateOrderCommand command = createOrderCommand(10L);
Order order = this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}
運行單元測試,打印以下 SQL:
// createOrder 方法中 repository.save(order) 產生的 SQL:
// 插入 收貨地址
Hibernate: insert into tb_order_address (detail) values (?)
// 插入 order
Hibernate: insert into tb_order (user_address_id, price, status, user_id) values (?, ?, ?, ?)
// 插入 orderItem
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
// 將 order item 與 order 進行綁定(這步存在性能損耗,但是目前沒有更好的解決方案)
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
是否發現 Spring Data Jpa 的強大之處:核心邏輯全部內聚在 Order 類,在沒有寫任何數據層訪問代碼的前提下,一個 save 方法便可以將這組高內聚的對象保存到 DB。
5.2. 修改地址
修改地址核心代碼如下:
@Transactional(readOnly = false)
public void modifyAddress(Long orderId, String address){
Optional<Order> orderOptional = repository.findById(orderId);
if (orderOptional.isPresent()){
Order order = orderOptional.get();
order.modifyAddress(address);
this.repository.save(order);
}
}
// Order 實體上的方法
public void modifyAddress(String address){
if (this.address == null){
this.address = new OrderAddress();
}
this.address.modify(address);
}
// OrderAddress 實體上的方法
public void modify(String address) {
setDetail(address);
}
首先,看一個添加地址的場景,生單時沒有提供收貨地址,生單後修改地址:
@Test
void modifyAddress_add() {
// 新訂單不存儲地址信息(沒有 userAddress)
Order order = null;
{
CreateOrderCommand command = createOrderCommand(20L);
// 將收穫地址設置爲 null
command.setUserAddress(null);
order = this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}
// 修改時,直接創建地址(插入新數據)
String address = "新增地址";
// Lazy 加載,只加載 orderAddress
// 修改後,只更新 OrderAddress
this.applicationService.modifyAddress(order.getId(), address);
Order orderInDB = this.repository.findById(order.getId()).get();
Assertions.assertEquals(address, orderInDB.getAddress().getDetail() );
}
運行單測可,控制檯輸出以下信息:
// createOrder 方法中 repository.save(order) 產生的 SQL:
// 生單時沒有地址,所以沒有向 tb_order_address 插入數據
Hibernate: insert into tb_order (user_address_id, price, status, user_id) values (?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
// modifyAddress 方法中 repository.findById(orderId) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
// modifyAddress 方法中 this.repository.save(order) 產生的 SQL
// 爲 Order 對象添加 orderAddress 後,自動向數據庫添加數據
Hibernate: insert into tb_order_address (detail) values (?)
// 更新 Order 的 user_address,完成數據綁定
Hibernate: update tb_order set user_address_id=?, price=?, status=?, user_id=? where id=?
// repository.findById(order.getId()) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象,進行結果檢測
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
看一個更新地址的場景,生單時設置收貨地址,然後操作修改地址:
@Test
void modifyAddress_update() {
// 新訂單部存在地址信息(沒有 userAddress)
Order order = null;
{
CreateOrderCommand command = createOrderCommand(30L);
order = this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}
// Lazy 加載,只加載 orderAddress
// 修改後,只更新 OrderAddress
String address = "修改地址";
this.applicationService.modifyAddress(order.getId(), address);
Order orderInDB = this.repository.findById(order.getId()).get();
Assertions.assertEquals(address, orderInDB.getAddress().getDetail() );
}
運行測試用例,輸出如下信息:
// createOrder 方法中 repository.save(order) 產生的 SQL:
// 創建帶有地址的訂單
Hibernate: insert into tb_order_address (detail) values (?)
Hibernate: insert into tb_order (user_address_id, price, status, user_id) values (?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
// modifyAddress 方法中 repository.findById(orderId) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
// 在對 order.address 進行訪問時,進行自動加載
Hibernate: select orderaddre0_.id as id1_1_0_, orderaddre0_.detail as detail2_1_0_ from tb_order_address orderaddre0_ where orderaddre0_.id=?
// modifyAddress 方法中 this.repository.save(order) 產生的 SQL
// OrderAddress 信息發生變化,將變更更新到數據庫
Hibernate: update tb_order_address set detail=? where id=?
// repository.findById(order.getId()) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象,進行結果檢測
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
從該用例可看出,Jpa 具有:
-
懶加載能力,只有在訪問到關聯數據時纔對數據進行加載
-
自動同步能力,新增對象通過 insert 將其插入數據庫,修改對象通過 update 對數據庫數據進行更新
5.3. 支付
修改地址是簡單的一對一,那對於較複雜的一對多,Jpa 是否也具有 懶加載 和 自動同步能力呢?
支付核心代碼如下:
@Transactional(readOnly = false)
public void paySuccess(PaySuccessCommand command){
Optional<Order> orderOptional = repository.findById(command.getOrderId());
if (orderOptional.isPresent()){
Order order = orderOptional.get();
order.paySuccess(command);
this.repository.save(order);
}
}
// Order 實體上的 paySuccess 方法
public void paySuccess(PaySuccessCommand paySuccessCommand){
this.setStatus(OrderStatus.PAID);
this.items.forEach(OrderItem::paySuccess);
}
// OrderItem 上的 paySuccess 方法
public void paySuccess() {
setStatus(OrderItemStatus.PAID);
}
單元測試如下:
@Test
void paySuccess() {
Order order = null;
{
CreateOrderCommand command = createOrderCommand(50L);
order = this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}
PaySuccessCommand paySuccessCommand = new PaySuccessCommand();
paySuccessCommand.setOrderId(order.getId());
paySuccessCommand.setPrice(1000L);
paySuccessCommand.setChanel("微信支付");
// Lazy 加載,只加載 orderItem
// 修改後,更新 order 和 OrderItem
this.applicationService.paySuccess(paySuccessCommand);
Order orderInDB = this.repository.findById(order.getId()).get();
Assertions.assertEquals(OrderStatus.PAID, orderInDB.getStatus());
orderInDB.getItems().forEach(orderItem -> {
Assertions.assertEquals(OrderItemStatus.PAID, orderItem.getStatus());
});
}
運行單元測試,控制檯出現信息如下:
// createOrder 方法中 repository.save(order) 產生的 SQL:
// 創建帶有地址的訂單
Hibernate: insert into tb_order_address (detail) values (?)
Hibernate: insert into tb_order (user_address_id, price, status, user_id) values (?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: insert into tb_order_item (amount, price, product_id, product_name, status) values (?, ?, ?, ?, ?)
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
Hibernate: update tb_order_item set order_id=? where id=?
// paySuccess 方法中 repository.findById(orderId) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
// 訪問 order.items,觸發自動加載
Hibernate: select items0_.order_id as order_id7_2_0_, items0_.id as id1_2_0_, items0_.id as id1_2_1_, items0_.amount as amount2_2_1_, items0_.price as price3_2_1_, items0_.product_id as product_4_2_1_, items0_.product_name as product_5_2_1_, items0_.status as status6_2_1_ from tb_order_item items0_ where items0_.order_id=?
// paySuccess 方法中 this.repository.save(order) 產生的 SQL
// 將 Order 變更更新到數據庫
Hibernate: update tb_order set user_address_id=?, price=?, status=?, user_id=? where id=?
// 將 OrderItem 變更更新到數據庫
Hibernate: update tb_order_item set amount=?, price=?, product_id=?, product_name=?, status=? where id=?
Hibernate: update tb_order_item set amount=?, price=?, product_id=?, product_name=?, status=? where id=?
Hibernate: update tb_order_item set amount=?, price=?, product_id=?, product_name=?, status=? where id=?
Hibernate: update tb_order_item set amount=?, price=?, product_id=?, product_name=?, status=? where id=?
Hibernate: update tb_order_item set amount=?, price=?, product_id=?, product_name=?, status=? where id=?
// repository.findById(order.getId()) 產生的 SQL
// 從 DB 中加載數據,構建內存的 Order 對象,進行結果檢測
Hibernate: select order0_.id as id1_0_0_, order0_.user_address_id as user_add5_0_0_, order0_.price as price2_0_0_, order0_.status as status3_0_0_, order0_.user_id as user_id4_0_0_ from tb_order order0_ where order0_.id=?
從 SQL 中可見,在複雜的 一對多 場景,懶加載 和 自動同步能力 仍舊有效。
從代碼上可以清晰得出:在 Spring Data Jpa 的助力下,無需編寫任何數據層訪問代碼,便可以完成領域對象的管理。
6. 小結
DDD 和 Jpa 都是面向對象設計的巔峯之作,兩者結合威力巨大。
結合使用 DDD 和 JPA 可以有效地將領域模型與數據庫持久化技術相結合。開發人員可以使用領域驅動的方法管理數據,並通過 JPA 將數據存儲在數據庫中,從而避免冗長的數據持久化代碼。
此外,使用 DDD 和 JPA 還有其他優勢:
提高代碼可讀性:領域驅動的設計方法可以幫助開發人員更清晰地瞭解領域模型,使代碼更易於閱讀和維護。
減少代碼量:使用 JPA 可以減少代碼量,因爲開發人員不需要編寫手動的數據持久化代碼。
提高代碼的可重用性:通過使用領域模型,開發人員可以創建一組可重用的實體,並在多個地方使用它們。
提高代碼的可擴展性:使用 DDD 和 JPA 可以使代碼更易於擴展,因爲它們遵循領域驅動的設計方法。
總之,使用 DDD 和 JPA 可以幫助開發人員更有效地解決業務問題,提高代碼的可讀性,可重用性和可擴展性,並減少代碼量。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/tNB6D8MmEk9KXl-mU0p7mg