MyBatis Plus 的 CRUD 介面使用

2021-10-16 22:10:52 字數 3754 閱讀 2795

這篇文章來學習一下mybatisplus的crud介面具體使用,其中還是有幾個比較重要的點,當然你也可以檢視官網進行學習。

mybatisplus初使用:

mybatisplus官網:

mybatisplus官方示列:

1、insert插入操作

向user表中新增一條資料。

@runwith

(springrunner.

class

)@springboottest

public

class

crudtests

}

注意:資料庫插入id值預設為:全域性唯一id

2、主鍵策略

上面向資料庫中插入一條記錄時,並沒有指定主鍵id的值,但資料庫中該字段有值,這是由於mybatisplus提供了主鍵生成策略,當我們在類的屬性上新增@tableid註解時,表明該欄位為主鍵,下面來看一下主鍵生成策略有哪些?

此處mybatisplus版本為3.0.5,在3.3.0版本中,主鍵生成策略已改變,可以參考官方文件。

@tableid

(value =

"id"

, type = idtype.id_worker_str)

private long id;

mybatis-plus.

global

-config.db-config.id-

type

=auto

其它主鍵策略:分析 idtype 原始碼可知:

@getter

public

enum idtype

}

此部分,對應官方文件如下:

1、自動填充

專案中經常會遇到一些資料,每次都使用相同的方式填充,例如記錄的建立時間,更新時間等。我們可以使用mybatis plus的自動填充功能,完成這些欄位的自動賦值工作:

(1)、資料庫表中新增自動填充字段

在user表中新增datetime型別的新的字段 create_time、update_time

(2)、實體上新增註解

@data

public

class

user

(3)、實現元物件處理器介面

使用屬性自動填充時,要自定義實現類 mymetaobjecthandler注意:不要忘記新增 @component 註解

@component

public

class

mymetaobjecthandler

implements

metaobjecthandler

​ // 屬性字段更新時,會執行此方法

@override

public

void

updatefill

(metaobject metaobject)

}

1、根據id查詢記錄

@test

public

void

testselectbyid()

2、通過多個id批量查詢

完成了動態sql的foreach的功能

@test

public

void

testselectbatchids()

3、簡單的條件查詢

通過map封裝查詢條件

@test

public

void

testselectbymap()

注意:map中的key對應的是資料庫中的列名。例如資料庫user_id,實體類是userid,這時map的key需要填寫user_id

4、分頁

mybatis plus自帶分頁外掛程式,只要簡單的配置即可實現分頁功能

(1)、建立配置類

// 分頁外掛程式

@bean

public paginationinterceptor paginationinterceptor()

(2)、測試selectpage分頁

@test

public

void

testselectpage()

1、根據id刪除記錄

@test

public

void

testdeletebyid()

2、批量刪除

@test

public

void

testdeletebatchids()

3、簡單的條件查詢刪除

@test

public

void

testdeletebymap()

4、邏輯刪除

物理刪除:真實刪除,將對應資料從資料庫中刪除,之後查詢不到此條被刪除資料

邏輯刪除:假刪除,將對應資料中代表是否被刪除字段狀態修改為「被刪除狀態」,之後在資料庫中仍舊能看到此條資料記錄

(1)、資料庫中新增 deleted欄位

alter table `user` add column `deleted` boolean
(2)、實體類新增 deleted 字段

並加上 @tablelogic 註解 和 @tablefield(fill = fieldfill.insert) 註解

@tablelogic

@tablefield

(fill = fieldfill.insert)

private integer deleted;

(3)、元物件處理器介面新增deleted的insert預設值

@override

public

void

insertfill

(metaobject metaobject)

此為預設值,如果你的預設值和mp預設的一樣,該配置可無

mybatis-plus.global-config.db-config.logic-delete-value=

1mybatis-plus.global-config.db-config.logic-not-delete-value=

0

Golang連線MySQL資料庫之CRUD

我們這次來學習使用golang來連線mysql資料庫,並使用golang實現資料庫的crud操作。首先我們建立乙個golang的專案,並配置專案gopath,這一步可以參考我的部落格golang環境安裝 idea開發golang。golang的專案環境搭建完成之後,我們還需要建立一張資料庫表。為了能...

mybatis plus分頁步驟

控制器層 需要傳入兩個引數page 當前頁數 limit 每頁數量 獲取分頁資料 page page1 new page page,limit page1 noticeservice.getpagenotice page1 listnotices page1.getrecords 介面 pagege...

mybatis plus 聯合查詢

在xml中只需要需要寫如下的 即可實現分頁 select from user where name like concat 呼叫方法 分頁外掛程式 public static void testpagelistuser 貢獻一波自己的 1 呼叫 pagepage new page current,l...