欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mybatis-Plus接口BaseMapper與Services使用詳解

 更新時(shí)間:2022年05月26日 11:51:26   作者:把蘋(píng)果咬哭的測(cè)試筆記  
這篇文章主要為大家介紹了Mybatis-Plus接口BaseMapper與Services使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

最近在工作開(kāi)發(fā)中遇到一個(gè)批量新增修改的處理,我使用的是 mybatis-plus,但是在用的 BaseMapper 接口里是沒(méi)有這個(gè)方法的,后來(lái)發(fā)現(xiàn) Service 接口里有這個(gè)方法,今天整理一下這2種用法。

一、使用 BaseMapper 接口

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

以為項(xiàng)目中的代碼為例,我有一個(gè)實(shí)體類(lèi)User,需要對(duì)其進(jìn)行CRUD,那么我直接在 DAO 層去繼承 BaseMapper 接口即可。

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

這樣我就可以直接使用里面的各種API了,非常的方便。另外,我發(fā)現(xiàn)了一個(gè)mybatis-plus的簡(jiǎn)潔教程,可以很方便的查詢(xún)一些知識(shí)點(diǎn),文末自取。

但是后來(lái)在開(kāi)發(fā)過(guò)程中,發(fā)現(xiàn)BaseMapper接口中的insert()不能滿(mǎn)足我的需求了,而在Service接口中,發(fā)現(xiàn)有個(gè)saveOrUpdateBatch()可以使用,果斷擁抱之。

二、使用 Service 接口

除了 BaseMapper 接口,MyBatis Plus 還提供了 IService 接口,該接口對(duì)應(yīng) Service 層。MyBatis Plus 的通用 Service CRUD 實(shí)現(xiàn)了 IService 接口,進(jìn)一步封裝 CRUD。為了避免與 BaseMapper 中定義的方法混淆,該接口使用 get(查詢(xún)單行)、remove(刪除)、list(查詢(xún)集合)和 page(分頁(yè))前綴命名的方式進(jìn)行區(qū)別。

這個(gè)既然是對(duì)應(yīng) Service 接口,那么也就要用在 service 層。

還是要處理剛才的User類(lèi),DAO 層仍然是需要的:

@Mapper
public interface AddressListMapper extends BaseMapper<User>{

}

然后在 service 層的接口繼承IService,泛型是User實(shí)體類(lèi):

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

最后在 service 的實(shí)現(xiàn)層中,繼承ServiceImpl,泛型中傳入mapper和實(shí)體類(lèi):

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

}

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

我使用的是saveOrUpdateBatch,這個(gè)要注意下,是通過(guò)自定義的唯一索引進(jìn)行批量保存更新的,所以我要去實(shí)體類(lèi)User中使用@TableId標(biāo)記出唯一索性。

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

最后,放上教程鏈接:http://www.dbjr.com.cn/article/222180.htm

以上就是Mybatis-Plus接口BaseMapper與Services使用詳解的詳細(xì)內(nèi)容,更多關(guān)于Mybatis Plus接口的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論