ServiceImpl修改操作:用Mapper的update方法還是ServiceImpl自己的update方法?

ServiceImpl修改操作:用Mapper的update方法還是ServiceImpl自己的update方法?

Mapper與ServiceImpl數據操作實踐指南

在構建數據訪問層時,常常會用到Mapper和ServiceImpl類。本文重點討論在ServiceImpl中如何高效地實現數據修改操作。

ServiceImpl修改操作的最佳實踐

在ServiceImpl中,修改數據有兩種途徑:直接調用Mapper的update方法,或使用ServiceImpl自身封裝的update方法。

推薦方案:直接使用Mapper的update方法

我們建議優先選擇直接調用Mapper的update方法。原因如下:

  • 職責分明:Mapper專注于數據訪問,ServiceImpl負責業務邏輯。這種分工使代碼更清晰易維護。
  • 代碼復用:Mapper的update方法可被多個ServiceImpl復用,避免代碼冗余。
  • 一致性:使用Mapper的update方法能保證數據修改操作的一致性。

ServiceImpl的update方法詳解

雖然建議優先使用Mapper的update方法,但ServiceImpl中通常也包含update方法,其內部實現通常如下:

default boolean update(T entity, Wrapper<T> updateWrapper) {     return SqlHelper.retBool(getBaseMapper().update(entity, updateWrapper)); }

此方法最終還是調用了Mapper的update方法。因此,僅在需要在修改操作前后添加額外業務邏輯時才考慮使用ServiceImpl的update方法。

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享