0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

用好DDD必須先過Spring Data這關(guān)

jf_ro2CN3Fa ? 來源:芋道源碼 ? 2023-03-07 09:38 ? 次閱讀


1. 面向?qū)ο笤O(shè)計是 DDD 的核心

DDD 著重于將業(yè)務(wù)領(lǐng)域中的概念和對象映射到對象中,使對象模型能夠更好地反映業(yè)務(wù)的真實情況,從而使設(shè)計更具可理解性和可維護(hù)性。

DDD 是一種領(lǐng)域驅(qū)動的設(shè)計方法,旨在通過建立對領(lǐng)域模型的清晰理解來解決業(yè)務(wù)問題。和事務(wù)腳本不同,DDD 使用面向?qū)ο笤O(shè)計來應(yīng)對復(fù)雜的業(yè)務(wù)場景。

簡單來說,DDD 是由領(lǐng)域?qū)ο蟪休d業(yè)務(wù)邏輯,所有的業(yè)務(wù)操作均在模型對象上完成,同一對象上不同的業(yè)務(wù)操作構(gòu)成了對象的生命周期。

我們以訂單為例,如下圖所示:

d2e30e6c-bc7d-11ed-bfe3-dac502259ad0.png
  1. 首先,用戶操作下單,使用提交數(shù)據(jù)為其創(chuàng)建一個 Order 對象,版本 V1;
  2. 隨后,用戶進(jìn)行改地址操作,調(diào)用 Order 對象的 modifyAddress 方法,Order 從原來的 V1 變成 V2;
  3. 用戶完成支付后,調(diào)用 Order 對象的 paySuccess 方法,Order 從 V2 變成 V3;

從圖上可見,在 DDD 設(shè)計中,所有的業(yè)務(wù)邏輯均由業(yè)務(wù)對象完成,所以面向?qū)ο笫?DDD 設(shè)計的核心。

基于 Spring Boot + MyBatis Plus + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能

  • 項目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 視頻教程:https://doc.iocoder.cn/video/

2. 為什么需要 Repository?

假設(shè),有一臺非常牛逼的計算機,計算資源無限、內(nèi)存大小無限、永不掉電、永不宕機,那最簡單高效的方式便是將模型對象全部放在內(nèi)存中。

但,現(xiàn)實不存在這樣的機器,我們不得不將內(nèi)存對象寫入磁盤,下次使用時,在將其從磁盤讀入到內(nèi)存。

整體結(jié)構(gòu)如下圖所示:

d2fbfcce-bc7d-11ed-bfe3-dac502259ad0.png

和上圖相比,具有如下特點:

  1. 業(yè)務(wù)操作沒變,仍舊依次完成 下單、改地址、支付等操作

  2. 引入持久化存儲(MySQL),可以將 Order 對象存儲于關(guān)系數(shù)據(jù)庫

  3. 配合 Order 的生命周期,操作中增加 save、load 和 update 等操作

  • 用戶下單創(chuàng)建 Order 對象,通過 save 方法將 Order 對象持久化到 DB
  • 接收到業(yè)務(wù)操作,需執(zhí)行l(wèi)oad,從 DB 加載數(shù)據(jù)到內(nèi)存 并對 Order 對象的狀態(tài)進(jìn)行恢復(fù)
  • 在業(yè)務(wù)操作完成后,需執(zhí)行update,將 Order 對象的最新狀態(tài)同步的 DB

相對全內(nèi)存版本確實增加了不小的復(fù)雜性,為了更好的對這些復(fù)雜性進(jìn)行管理,引入 Repository 模式。

在領(lǐng)域驅(qū)動設(shè)計(DDD)中,Repository 是一種設(shè)計模式,它是用來存儲領(lǐng)域?qū)ο蟮娜萜?。它提供了一種統(tǒng)一的方式來查詢和存儲領(lǐng)域?qū)ο蟆?code style="font-size:14px;padding:2px 4px;margin-right:2px;margin-left:2px;color:rgb(30,107,184);background-color:rgba(27,31,35,.05);font-family:'Operator Mono', Consolas, Monaco, Menlo, monospace;">Repository提供了對底層數(shù)據(jù)存儲的抽象,允許應(yīng)用程序在沒有直接與數(shù)據(jù)存儲技術(shù)交互的情況下訪問數(shù)據(jù),同時該抽象允許在不修改應(yīng)用程序代碼的情況下更改數(shù)據(jù)存儲技術(shù)。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能

  • 項目地址:https://github.com/YunaiV/yudao-cloud
  • 視頻教程:https://doc.iocoder.cn/video/

3. 什么才是好的 Repository ?

好的 Repository 應(yīng)該在滿足業(yè)務(wù)需求的前提下,具備以下特性:

  1. 高內(nèi)聚: 好的 Repository 應(yīng)該滿足單一職責(zé)原則,每個 Repository 只關(guān)注一種領(lǐng)域?qū)ο蟮拇鎯Γ?/li>
  2. 耦合 好的 Repository 應(yīng)該通過抽象接口與其他層進(jìn)行交互,保證它們之間的耦合度低;
  3. 簡單易用: 好的 Repository 應(yīng)該提供一組易于使用的方法,方便開發(fā)人員使用;
  4. 可維護(hù)性: 好的 Repository 應(yīng)該易于維護(hù),維護(hù)人員不需要長時間閱讀代碼才能了解它的工作原理;

說的太官方了,用人話就是:

  1. 需要一個統(tǒng)一的 Repository 接口,用于對易用方法save、load、update進(jìn)行管理
  2. 為每個聚合根創(chuàng)建一個 Repository 接口,繼承自 統(tǒng)一Repository,只關(guān)注該聚合根的存儲
  3. Repository 的實現(xiàn)盡可能的簡單,最好不用實現(xiàn)(人都是懶的)

4. 初始 Spring Data

Spring Data是一個框架,旨在簡化數(shù)據(jù)訪問層的開發(fā)。它通過抽象和模板化方法,使得與各種數(shù)據(jù)存儲(如關(guān)系型數(shù)據(jù)庫,文檔數(shù)據(jù)庫,圖形數(shù)據(jù)庫,緩存等)的交互變得更加簡單和標(biāo)準(zhǔn)化。

Spring Data 通過提供簡單的、通用的數(shù)據(jù)訪問接口(如Repository)和自動生成實現(xiàn)代碼,使得開發(fā)人員不必編寫重復(fù)的數(shù)據(jù)訪問代碼。這樣,開發(fā)人員可以專注于業(yè)務(wù)邏輯,而無需關(guān)注數(shù)據(jù)存儲和訪問的細(xì)節(jié)。

總的來說,Spring Data的主要解決的問題是:簡化數(shù)據(jù)訪問層的開發(fā),提高代碼復(fù)用性,降低開發(fā)復(fù)雜度。

Spring Data 對多種數(shù)據(jù)存儲提供了支持,本文以 Spring Data Jpa 為例,快速實現(xiàn)應(yīng)用程序與關(guān)系數(shù)據(jù)庫的交互。

4.1. 引入 Spring Data Jpa

Spring Data JPA 是 Spring Data 家族的重要成員,主要解決 Java 應(yīng)用程序使用 JPA 完成對數(shù)據(jù)庫的訪問問題。它提供了一種簡單而靈活的方法來訪問和管理數(shù)據(jù),并且可以消除重復(fù)代碼和提高開發(fā)效率。

首先,需要在pom中 引入 spring-data-jpa-starter,具體如下:


org.springframework.boot
spring-boot-starter-data-jpa

其次,引入 MySQL 驅(qū)動,具體如下:


com.mysql
mysql-connector-j
runtime

Spring Data Jpa 默認(rèn)實現(xiàn)是 Hibernate,而 Hibernate 是目前最流行且功能最強大的 JPA 實現(xiàn),它提供了強大的映射、查詢和事務(wù)管理能力。

4.2. 完成配置

在 application.yml 增加 DB 和 Jpa 相關(guān)配置,具體如下:

spring:
application:
name:Spring-Data-for-DDD-demo
datasource:
#數(shù)據(jù)庫配置信息
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
//開啟SpringDataJpa,basePackages是Repository接口存放的包路徑
@EnableJpaRepositories(basePackages="com.geekhalo.springdata4ddd.order.repository")
publicclassApplication{

publicstaticvoidmain(String[]args){
SpringApplication.run(Application.class,args);
}

}

4.3. 使用 Repository

一切就緒,接下來就可以為模型創(chuàng)建專屬 Repository,具體如下:

publicinterfaceOrderCommandRepositoryextendsJpaRepository<Order,Long>{
}

至此,Order 的專屬 Repository 就開發(fā)完成。

不知道你是否存在疑問:

  1. 說好的統(tǒng)一的易用方法在哪里?
  2. 為什么沒有看到實現(xiàn)代碼?

一般情況下,JpaRepository 接口中的方法就能滿足大部分需求,典型方法包括:

d3272598-bc7d-11ed-bfe3-dac502259ad0.png

5. 實戰(zhàn)--訂單

為了體現(xiàn) Spring Data Jpa的強大功能,以最常見的訂單為例,業(yè)務(wù)模型如下圖所示:

d33d7dde-bc7d-11ed-bfe3-dac502259ad0.png
  1. 一筆下單對應(yīng)一個訂單(Order
  2. 一個訂單可以有一個收獲地址(OrderAddress
  3. 一個訂單可以關(guān)聯(lián)多個訂單項(OrderItem

對應(yīng)到領(lǐng)域模型如下:

d3582846-bc7d-11ed-bfe3-dac502259ad0.png

核心代碼如下:

@Data
@Entity
@Table(name="tb_order")
@Setter(AccessLevel.PRIVATE)
publicclassOrder{

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
privateLongid;

@Column(name="user_id")
privateLonguserId;

@Column(name="status")
@Enumerated(EnumType.STRING)
privateOrderStatusstatus;

@Column(name="price")
privateintprice;

//收貨地址
@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="user_address_id")
privateOrderAddressaddress;

//訂單項
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumn(name="order_id")
privateListitems=newArrayList<>();

}

5.1. 生單

先簡單看下生單的核心代碼,具體如下:

@Transactional(readOnly=false)
publicOrdercreateOrder(CreateOrderCommandcommand){
//創(chuàng)建內(nèi)存對象
Orderorder=Order.create(command);
//保存到數(shù)據(jù)庫
this.repository.save(order);
returnorder;
}

//Order實體上的create方法
publicstaticOrdercreate(CreateOrderCommandcommand){
//創(chuàng)建內(nèi)存對象
Orderorder=newOrder();
order.setUserId(command.getUserId());

StringuserAddress=command.getUserAddress();
if(!StringUtils.hasText(userAddress)){
//設(shè)置收獲地址
OrderAddressorderAddress=newOrderAddress();
orderAddress.setDetail(userAddress);
order.setAddress(orderAddress);
}

//添加訂單項
ListproductForBuys=command.getProducts();
productForBuys.stream()
.map(productForBuy->OrderItem.create(productForBuy))
.forEach(orderItem->order.addOrderItem(orderItem));

order.init();
returnorder;
}

單元測試,具體如下:

@Test
voidcreateOrder(){
//創(chuàng)訂單,將整個Order聚合根全部保存到數(shù)據(jù)庫,包括
//1.order
//2.orderItem
//3.orderAddress
CreateOrderCommandcommand=createOrderCommand(10L);
Orderorder=this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}

運行單元測試,打印以下 SQL:

//createOrder方法中repository.save(order)產(chǎn)生的SQL:
//插入收貨地址
Hibernate:insertintotb_order_address(detail)values(?)
//插入order
Hibernate:insertintotb_order(user_address_id,price,status,user_id)values(?,?,?,?)
//插入orderItem
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
//將orderitem與order進(jìn)行綁定(這步存在性能損耗,但是目前沒有更好的解決方案)
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?

是否發(fā)現(xiàn) Spring Data Jpa 的強大之處:核心邏輯全部內(nèi)聚在 Order 類,在沒有寫任何數(shù)據(jù)層訪問代碼的前提下,一個 save 方法便可以將這組高內(nèi)聚的對象保存到 DB。

5.2. 修改地址

修改地址核心代碼如下:

@Transactional(readOnly=false)
publicvoidmodifyAddress(LongorderId,Stringaddress){
OptionalorderOptional=repository.findById(orderId);
if(orderOptional.isPresent()){
Orderorder=orderOptional.get();
order.modifyAddress(address);
this.repository.save(order);
}
}

//Order實體上的方法
publicvoidmodifyAddress(Stringaddress){
if(this.address==null){
this.address=newOrderAddress();
}
this.address.modify(address);
}

//OrderAddress實體上的方法
publicvoidmodify(Stringaddress){
setDetail(address);
}

首先,看一個添加地址的場景,生單時沒有提供收貨地址,生單后修改地址:

d36f609c-bc7d-11ed-bfe3-dac502259ad0.png

@Test
voidmodifyAddress_add(){
//新訂單不存儲地址信息(沒有userAddress)
Orderorder=null;
{
CreateOrderCommandcommand=createOrderCommand(20L);
//將收獲地址設(shè)置為null
command.setUserAddress(null);
order=this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}

//修改時,直接創(chuàng)建地址(插入新數(shù)據(jù))
Stringaddress="新增地址";
//Lazy加載,只加載orderAddress
//修改后,只更新OrderAddress
this.applicationService.modifyAddress(order.getId(),address);

OrderorderInDB=this.repository.findById(order.getId()).get();
Assertions.assertEquals(address,orderInDB.getAddress().getDetail());
}

運行單測可,控制臺輸出以下信息:

//createOrder方法中repository.save(order)產(chǎn)生的SQL:
//生單時沒有地址,所以沒有向tb_order_address插入數(shù)據(jù)
Hibernate:insertintotb_order(user_address_id,price,status,user_id)values(?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?

//modifyAddress方法中repository.findById(orderId)產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?

//modifyAddress方法中this.repository.save(order)產(chǎn)生的SQL
//為Order對象添加orderAddress后,自動向數(shù)據(jù)庫添加數(shù)據(jù)
Hibernate:insertintotb_order_address(detail)values(?)
//更新Order的user_address,完成數(shù)據(jù)綁定
Hibernate:updatetb_ordersetuser_address_id=?,price=?,status=?,user_id=?whereid=?

//repository.findById(order.getId())產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象,進(jìn)行結(jié)果檢測
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?

看一個更新地址的場景,生單時設(shè)置收貨地址,然后操作修改地址:

@Test
voidmodifyAddress_update(){
//新訂單部存在地址信息(沒有userAddress)
Orderorder=null;
{
CreateOrderCommandcommand=createOrderCommand(30L);
order=this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}

//Lazy加載,只加載orderAddress
//修改后,只更新OrderAddress
Stringaddress="修改地址";
this.applicationService.modifyAddress(order.getId(),address);

OrderorderInDB=this.repository.findById(order.getId()).get();
Assertions.assertEquals(address,orderInDB.getAddress().getDetail());
}

運行測試用例,輸出如下信息:

//createOrder方法中repository.save(order)產(chǎn)生的SQL:
//創(chuàng)建帶有地址的訂單
Hibernate:insertintotb_order_address(detail)values(?)
Hibernate:insertintotb_order(user_address_id,price,status,user_id)values(?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?

//modifyAddress方法中repository.findById(orderId)產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?
//在對order.address進(jìn)行訪問時,進(jìn)行自動加載
Hibernate:selectorderaddre0_.idasid1_1_0_,orderaddre0_.detailasdetail2_1_0_fromtb_order_addressorderaddre0_whereorderaddre0_.id=?

//modifyAddress方法中this.repository.save(order)產(chǎn)生的SQL
//OrderAddress信息發(fā)生變化,將變更更新到數(shù)據(jù)庫
Hibernate:updatetb_order_addresssetdetail=?whereid=?

//repository.findById(order.getId())產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象,進(jìn)行結(jié)果檢測
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?

從該用例可看出,Jpa 具有:

  1. 懶加載能力,只有在訪問到關(guān)聯(lián)數(shù)據(jù)時才對數(shù)據(jù)進(jìn)行加載
  2. 自動同步能力,新增對象通過 insert 將其插入數(shù)據(jù)庫,修改對象通過 update 對數(shù)據(jù)庫數(shù)據(jù)進(jìn)行更新

5.3. 支付

修改地址是簡單的一對一,那對于較復(fù)雜的一對多,Jpa 是否也具有 懶加載 和 自動同步能力呢?

支付核心代碼如下:

@Transactional(readOnly=false)
publicvoidpaySuccess(PaySuccessCommandcommand){
OptionalorderOptional=repository.findById(command.getOrderId());
if(orderOptional.isPresent()){
Orderorder=orderOptional.get();
order.paySuccess(command);
this.repository.save(order);
}
}

//Order實體上的paySuccess方法
publicvoidpaySuccess(PaySuccessCommandpaySuccessCommand){
this.setStatus(OrderStatus.PAID);
this.items.forEach(OrderItem::paySuccess);
}
//OrderItem上的paySuccess方法
publicvoidpaySuccess(){
setStatus(OrderItemStatus.PAID);
}

單元測試如下:

@Test
voidpaySuccess(){
Orderorder=null;
{
CreateOrderCommandcommand=createOrderCommand(50L);
order=this.applicationService.createOrder(command);
Assertions.assertNotNull(order.getId());
}

PaySuccessCommandpaySuccessCommand=newPaySuccessCommand();
paySuccessCommand.setOrderId(order.getId());
paySuccessCommand.setPrice(1000L);
paySuccessCommand.setChanel("微信支付");
//Lazy加載,只加載orderItem
//修改后,更新order和OrderItem
this.applicationService.paySuccess(paySuccessCommand);
OrderorderInDB=this.repository.findById(order.getId()).get();
Assertions.assertEquals(OrderStatus.PAID,orderInDB.getStatus());
orderInDB.getItems().forEach(orderItem->{
Assertions.assertEquals(OrderItemStatus.PAID,orderItem.getStatus());
});
}

運行單元測試,控制臺出現(xiàn)信息如下:

//createOrder方法中repository.save(order)產(chǎn)生的SQL:
//創(chuàng)建帶有地址的訂單
Hibernate:insertintotb_order_address(detail)values(?)
Hibernate:insertintotb_order(user_address_id,price,status,user_id)values(?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:insertintotb_order_item(amount,price,product_id,product_name,status)values(?,?,?,?,?)
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?
Hibernate:updatetb_order_itemsetorder_id=?whereid=?

//paySuccess方法中repository.findById(orderId)產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?
//訪問order.items,觸發(fā)自動加載
Hibernate:selectitems0_.order_idasorder_id7_2_0_,items0_.idasid1_2_0_,items0_.idasid1_2_1_,items0_.amountasamount2_2_1_,items0_.priceasprice3_2_1_,items0_.product_idasproduct_4_2_1_,items0_.product_nameasproduct_5_2_1_,items0_.statusasstatus6_2_1_fromtb_order_itemitems0_whereitems0_.order_id=?

//paySuccess方法中this.repository.save(order)產(chǎn)生的SQL
//將Order變更更新到數(shù)據(jù)庫
Hibernate:updatetb_ordersetuser_address_id=?,price=?,status=?,user_id=?whereid=?
//將OrderItem變更更新到數(shù)據(jù)庫
Hibernate:updatetb_order_itemsetamount=?,price=?,product_id=?,product_name=?,status=?whereid=?
Hibernate:updatetb_order_itemsetamount=?,price=?,product_id=?,product_name=?,status=?whereid=?
Hibernate:updatetb_order_itemsetamount=?,price=?,product_id=?,product_name=?,status=?whereid=?
Hibernate:updatetb_order_itemsetamount=?,price=?,product_id=?,product_name=?,status=?whereid=?
Hibernate:updatetb_order_itemsetamount=?,price=?,product_id=?,product_name=?,status=?whereid=?

//repository.findById(order.getId())產(chǎn)生的SQL
//從DB中加載數(shù)據(jù),構(gòu)建內(nèi)存的Order對象,進(jìn)行結(jié)果檢測
Hibernate:selectorder0_.idasid1_0_0_,order0_.user_address_idasuser_add5_0_0_,order0_.priceasprice2_0_0_,order0_.statusasstatus3_0_0_,order0_.user_idasuser_id4_0_0_fromtb_orderorder0_whereorder0_.id=?

從 SQL 中可見,在復(fù)雜的 一對多 場景,懶加載 和 自動同步能力 仍舊有效。

從代碼上可以清晰得出:在 Spring Data Jpa 的助力下,無需編寫任何數(shù)據(jù)層訪問代碼,便可以完成領(lǐng)域?qū)ο蟮墓芾怼?/p>

6. 小結(jié)

DDD 和 Jpa 都是面向?qū)ο笤O(shè)計的巔峰之作,兩者結(jié)合威力巨大。

結(jié)合使用 DDD 和 JPA 可以有效地將領(lǐng)域模型與數(shù)據(jù)庫持久化技術(shù)相結(jié)合。開發(fā)人員可以使用領(lǐng)域驅(qū)動的方法管理數(shù)據(jù),并通過 JPA 將數(shù)據(jù)存儲在數(shù)據(jù)庫中,從而避免冗長的數(shù)據(jù)持久化代碼。

此外,使用 DDD 和 JPA 還有其他優(yōu)勢:

  • 提高代碼可讀性: 領(lǐng)域驅(qū)動的設(shè)計方法可以幫助開發(fā)人員更清晰地了解領(lǐng)域模型,使代碼更易于閱讀和維護(hù)。
  • 減少代碼量: 使用 JPA 可以減少代碼量,因為開發(fā)人員不需要編寫手動的數(shù)據(jù)持久化代碼。
  • 提高代碼的可重用性: 通過使用領(lǐng)域模型,開發(fā)人員可以創(chuàng)建一組可重用的實體,并在多個地方使用它們。
  • 提高代碼的可擴(kuò)展性: 使用 DDD 和 JPA 可以使代碼更易于擴(kuò)展,因為它們遵循領(lǐng)域驅(qū)動的設(shè)計方法。

總之,使用 DDD 和 JPA 可以幫助開發(fā)人員更有效地解決業(yè)務(wù)問題,提高代碼的可讀性,可重用性和可擴(kuò)展性,并減少代碼量。



審核編輯 :李倩


聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • 數(shù)據(jù)庫
    +關(guān)注

    關(guān)注

    7

    文章

    3733

    瀏覽量

    64168
  • spring
    +關(guān)注

    關(guān)注

    0

    文章

    335

    瀏覽量

    14277
  • ddd
    ddd
    +關(guān)注

    關(guān)注

    0

    文章

    23

    瀏覽量

    2904

原文標(biāo)題:用好 DDD 必須先過 Spring Data 這關(guān)

文章出處:【微信號:芋道源碼,微信公眾號:芋道源碼】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。

收藏 人收藏

    評論

    相關(guān)推薦

    特斯拉豪賭中國工廠,必須先過資金和人才關(guān)

    特斯拉在2018年第四季度交付了63150輛Model 3, 2018年特斯拉汽車總交付量接近15萬輛。從側(cè)面證明了特斯拉確實在美國電動車市場銷售中占據(jù)了主導(dǎo)地位。但是有分析師表示,2019年
    發(fā)表于 02-13 11:24 ?1390次閱讀

    java spring教程

    java spring教程理解Spring 實現(xiàn)原理掌握Spring IOC,AOP掌握Spring的基礎(chǔ)配置和用法熟練使用SSH開發(fā)項目Sprin
    發(fā)表于 09-11 11:09

    什么是java spring

    什么是java springSpring是一個開源框架,它由Rod Johnson創(chuàng)建。它是為了解決企業(yè)應(yīng)用開發(fā)的復(fù)雜性而創(chuàng)建的。Spring使用基本的JavaBean來完成以前只可能由EJB完成
    發(fā)表于 09-11 11:16

    STM32為什么必須先配置時鐘再配置GPIO?

    STM32為什么必須先配置時鐘再配置GPIO?
    發(fā)表于 10-03 08:44

    基于maven的spring-data-redis整合

    spring和redis的整合
    發(fā)表于 04-12 14:03

    Spring工作原理

    2.AOP的主要原理:動態(tài)代理Spring工作原理Spring 已經(jīng)用過一段時間了,感覺Spring是個很不錯的框架。內(nèi)部最核心的就是IOC了,動態(tài)注入,讓一個對象的創(chuàng)建不用new了,可以自動的生產(chǎn),
    發(fā)表于 07-10 07:41

    springboot spring data jpa使用總結(jié)

    【本人禿頂程序員】springboot專輯:spring data jpa的使用
    發(fā)表于 04-15 11:38

    黑客攻防入門與進(jìn)階ddd

    黑客攻防入門與進(jìn)階ddd黑客攻防入門與進(jìn)階ddd
    發(fā)表于 02-23 15:45 ?8次下載

    Spring應(yīng)用 1 springXML配置說明

    開發(fā)過程。會使用注解形式的開發(fā)模式。但使用相應(yīng)的注解需要spring.xml中定義相應(yīng)的BeanProcessor,這樣顯得很笨重。 使用@Autowired注解,必須事先在Spring容器中聲明
    發(fā)表于 01-13 12:20 ?372次閱讀

    蘋果調(diào)查特斯拉為收購做準(zhǔn)備?先過了馬斯克關(guān)再說

    最近,蘋果完成對特斯拉的收購這樣的傳聞不絕于耳,再次負(fù)責(zé)任的告訴大家這是假消息,都是外媒的臆測,國內(nèi)媒體危言聳聽罷了,蘋果要收購特斯拉,先過了馬斯克這一關(guān)再說。
    發(fā)表于 05-14 15:33 ?1104次閱讀

    Spring認(rèn)證_什么是Spring GraphQL?

    數(shù)據(jù)整合 Spring GraphQL 支持使用 Querydsl 通過 Spring Data Querydsl 擴(kuò)展 來獲取數(shù)據(jù)。Querydsl 提供了一種靈活但類型安全的方法,通過使用注釋
    的頭像 發(fā)表于 08-09 11:31 ?563次閱讀
    <b class='flag-5'>Spring</b>認(rèn)證_什么是<b class='flag-5'>Spring</b> GraphQL?

    Spring Data JDBC - 如何使用自定義ID

    Spring Data JDBC,你應(yīng)該首先閱讀它的介紹和文章,它解釋了 Spring Data JDBC 上下文中的相關(guān)性。相信我,
    的頭像 發(fā)表于 06-28 16:18 ?814次閱讀
    <b class='flag-5'>Spring</b> <b class='flag-5'>Data</b> JDBC - 如何使用自定義ID

    "Scalable, Distributed Systems Using Akka, Spring Boot, DDD, and Java--轉(zhuǎn)"

    "Scalable, Distributed Systems Using Akka, Spring Boot, DDD, and Java--轉(zhuǎn)"
    發(fā)表于 12-01 18:06 ?6次下載
    "Scalable, Distributed Systems Using Akka, <b class='flag-5'>Spring</b> Boot, <b class='flag-5'>DDD</b>, and Java--轉(zhuǎn)"

    Spring干掉原生JVM?

    意味著,除了 Spring 誕生以來就支持的 Java 虛擬機,官方添加了使用 GraalVM 將 Spring 應(yīng)用編譯成原生鏡像的 beta 支持,這樣的話,就能提供一種新的方式來部署
    的頭像 發(fā)表于 05-05 09:25 ?489次閱讀
    <b class='flag-5'>Spring</b>干掉原生JVM?

    DDD是什么?DDD核心概念梳理

    DDD 是什么,DDD 的英文全稱是 Domain-Driven Design,翻譯過來就是領(lǐng)域驅(qū)動設(shè)計。
    的頭像 發(fā)表于 09-07 11:12 ?8070次閱讀
    <b class='flag-5'>DDD</b>是什么?<b class='flag-5'>DDD</b>核心概念梳理