【測試開發】使用 Mybatis-Plus 的 BaseMapper 接口與 Service 接口

最近在工作開發中遇到一個批量新增修改的處理,我使用的是 mybatis-plus,但是在用的 BaseMapper 接口裏是沒有這個方法的,後來發現 Service 接口裏有這個方法,今天整理一下這2種用法。

一、使用 BaseMapper 接口

MyBatis Plus 提供了通用的 Mapper 接口(即 BaseMapper 接口),該接口對應我們的 DAO 層。在該接口中,定義了我們常見的方法簽名,這樣就可以方便我們對錶進行操作。例如:查詢(select)、插入(insert)、更新(update)和刪除(delete)操作。

以爲項目中的代碼爲例,我有一個實體類User,需要對其進行CRUD,那麼我直接在 DAO 層去繼承 BaseMapper 接口即可。

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

這樣我就可以直接使用裏面的各種API了,非常的方便。另外,我發現了一個mybatis-plus的簡潔教程,可以很方便的查詢一些知識點,文末自取。

但是後來在開發過程中,發現BaseMapper接口中的insert()不能滿足我的需求了,而在Service接口中,發現有個saveOrUpdateBatch()可以使用,果斷擁抱之。

二、使用 Service 接口

除了 BaseMapper 接口,MyBatis Plus 還提供了 IService 接口,該接口對應 Service 層。MyBatis Plus 的通用 Service CRUD 實現了 IService 接口,進一步封裝 CRUD。爲了避免與 BaseMapper 中定義的方法混淆,該接口使用 get(查詢單行)、remove(刪除)、list(查詢集合)和 page(分頁)前綴命名的方式進行區別。

這個既然是對應 Service 接口,那麼也就要用在 service 層。

還是要處理剛纔的User類,DAO 層仍然是需要的:

@Mapper
public interface AddressListMapper extends BaseMapper<User>{

}

然後在 service 層的接口繼承IService,泛型是User實體類:

public interface AddressListService extends IService<User> {
    /**
     * 同步用戶信息到數據庫
     */
    void saveUsers();
}

最後在 service 的實現層中,繼承ServiceImpl,泛型中傳入mapper和實體類:

@Service
public class AddressListServiceImpl extends ServiceImpl<AddressListMapper, User> implements AddressListService {

}

現在就可以使用 mybaits-plus service接口中提供的api了。

我使用的是saveOrUpdateBatch,這個要注意下,是通過自定義的唯一索引進行批量保存更新的,所以我要去實體類User中使用@TableId標記出唯一索性。

    /**
     * 郵箱
     */
    @TableId
    private String email;

最後,放上教程鏈接:https://www.hxstrive.com/subject/mybatis_plus/257.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章