MyBatis-Plus如何最優(yōu)雅最簡潔地完成數(shù)據(jù)庫操作
引言
兩點(diǎn):
一,使用MyBatis-Plus最新版(3.0.1)完成相關(guān)操作
二,好久沒寫MyBatis操作數(shù)據(jù)庫的博文了,有沒有想我啊,哈哈,認(rèn)真看,認(rèn)真聽,認(rèn)真學(xué)。
測(cè)試效果:

使用swagger2顯示API接口

swagge2 接口以及model信息

分頁接口測(cè)試.png
下面聽我細(xì)細(xì)道來,MyBatis-Plus的優(yōu)雅、簡潔與強(qiáng)大。
代碼生成器
代碼生成器,又被叫做逆向工程,MyBatis官方為了推廣,自己也寫了一個(gè),我之前也使用這個(gè),功能也是非常強(qiáng)大,強(qiáng)大以為支持自定義配置,那么問題來了,我該怎么配置才合理呢,所以,有人把所有的配置項(xiàng)都弄成中文的,還有人開發(fā)了生成插件,這些在我以往的博文中都看看到。MyBatis-Plus的代碼生成器到底怎么樣,這我就不評(píng)判了,我就這樣說,用用看吧。
在MyBatis-Plus的官網(wǎng)文檔中,有將代碼生成器的問題,有配置詳解,也有項(xiàng)目示例代碼,復(fù)制來就可用。
我這次是用MP 3.0.1,也就是最新版,官方還沒有更新呢,所以,我去找了很久的源碼,才將這個(gè)完成,勉強(qiáng)適合自己的了。這個(gè)在 CodeGenerator Module中,可以下下下來,導(dǎo)入到IDE中,看一下,修改配置就能運(yùn)行。有問題,也可以與我討論。
功能列表:
[?] 自動(dòng)生成model類
[?] 自動(dòng)生成dao接口
[?] 自動(dòng)生成xml文件
[?] 自動(dòng)生成service接口
[?] 自動(dòng)生成service實(shí)現(xiàn)類
[?] model支持Builder模式
[?] 支持swagger2
[?] 支持生成數(shù)據(jù)庫字段常量
[?] 支持生成Kotlin代碼
[] ......
項(xiàng)目初始化
第一步:pom.xml引入MyBatis-Plus依賴,注意,不需要再引入MyBatis的包,因?yàn)槲疫@里使用Spring Boot搭建的工程,所有因?yàn)榉绞揭娤拢?/p>
<dependencies>
...
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>
...
</dependencies>
第二步:將生成的代碼,拷貝到相應(yīng)的包下

代碼目錄結(jié)構(gòu)
第三步:在配置文件中進(jìn)行相應(yīng)的配置
具體配置可參考官網(wǎng),這里需要注意這樣幾個(gè)地方:
mybatis-plus:
# xml
mapper-locations: classpath:mapper/*Mapper.xml
# 實(shí)體掃描,多個(gè)package用逗號(hào)或者分號(hào)分隔
type-aliases-package: com.fengwenyi.mp3demo.model
configuration:
# 這個(gè)配置會(huì)將執(zhí)行的sql打印出來,在開發(fā)或測(cè)試的時(shí)候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
日志:分頁查詢
第四步:在啟動(dòng)類上添加下面的注解
@EnableTransactionManagement
@MapperScan("com.fengwenyi.mp3demo.dao")
增刪改
Service
我們一起去看源碼 com.baomidou.mybatisplus.extension.service.IService<T>
增加:
/**
* <p>
* 插入一條記錄(選擇字段,策略插入)
* </p>
*
* @param entity 實(shí)體對(duì)象
*/
boolean save(T entity);
修改:
/**
* <p>
* 根據(jù) ID 選擇修改
* </p>
*
* @param entity 實(shí)體對(duì)象
*/
boolean updateById(T entity);
/**
* <p>
* 根據(jù) whereEntity 條件,更新記錄
* </p>
*
* @param entity 實(shí)體對(duì)象
* @param updateWrapper 實(shí)體對(duì)象封裝操作類
* {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);刪除:
/**
* <p>
* 根據(jù) ID 刪除
* </p>
*
* @param id 主鍵ID
*/
boolean removeById(Serializable id);
/**
* <p>
* 根據(jù) entity 條件,刪除記錄
* </p>
*
* @param queryWrapper 實(shí)體包裝類
* {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
boolean remove(Wrapper<T> queryWrapper);Mapper
com.baomidou.mybatisplus.core.mapper.BaseMapper<T>
增加:
/**
* <p>
* 插入一條記錄
* </p>
*
* @param entity 實(shí)體對(duì)象
*/
int insert(T entity);
修改:
/**
* <p>
* 根據(jù) whereEntity 條件,更新記錄
* </p>
*
* @param entity 實(shí)體對(duì)象 (set 條件值,不能為 null)
* @param updateWrapper 實(shí)體對(duì)象封裝操作類(可以為 null,里面的 entity 用于生成 where 語句)
*/
int update(@Param(Constants.ENTITY) T entity,
@Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* <p>
* 根據(jù) ID 修改
* </p>
*
* @param entity 實(shí)體對(duì)象
*/
int updateById(@Param(Constants.ENTITY) T entity);刪除:
? ? /** ? ? ?* <p> ? ? ?* 根據(jù) entity 條件,刪除記錄 ? ? ?* </p> ? ? ?* ? ? ?* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null) ? ? ?*/ ? ? int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); ? ? /** ? ? ?* <p> ? ? ?* 根據(jù) ID 刪除 ? ? ?* </p> ? ? ?* ? ? ?* @param id 主鍵ID ? ? ?*/ ? ? int deleteById(Serializable id);
以上相當(dāng)于是常用API了,我們?nèi)タ纯矗窃趺磳?shí)現(xiàn)的。毫無疑問,Mapper是底層,Service調(diào)用Mapper去執(zhí)行sql,完成相關(guān)操作,所以,你完全可以直接調(diào)用Mapper完成相關(guān)操作,就跟使用MyBatis一樣。下面我們?nèi)タ纯?,他幫我們寫的Service是什么樣子,這里只看一個(gè)修改操作吧。
接口:
/**
* <p>
* 根據(jù) whereEntity 條件,更新記錄
* </p>
*
* @param entity 實(shí)體對(duì)象
* @param updateWrapper 實(shí)體對(duì)象封裝操作類
* {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
*/
boolean update(T entity, Wrapper<T> updateWrapper);
實(shí)現(xiàn):
@Override
public boolean update(T entity, Wrapper<T> updateWrapper) {
return ServiceImpl.retBool(baseMapper.update(entity, updateWrapper));
}
/**
* <p>
* 判斷數(shù)據(jù)庫操作是否成功
* </p>
* <p>
* 注意??! 該方法為 Integer 判斷,不可傳入 int 基本類型
* </p>
*
* @param result 數(shù)據(jù)庫操作返回影響條數(shù)
* @return boolean
*/
protected static boolean retBool(Integer result) {
return SqlHelper.retBool(result);
}
/**
* <p>
* 判斷數(shù)據(jù)庫操作是否成功
* </p>
*
* @param result 數(shù)據(jù)庫操作返回影響條數(shù)
* @return boolean
*/
public static boolean retBool(Integer result) {
return null != result && result >= 1;
}哈哈,是不是我們自己也會(huì)這樣寫啊!
查詢
接下來,我們一起討論下查詢吧。
MP 3.x,查詢接口發(fā)生了很大的變化,反正我是不喜歡的,你就弄一個(gè)什么開頭啊,到時(shí)候,我一點(diǎn)就知道有哪些方法了,他這里有 list*, get*,反正就是一個(gè)字——沒必要。
先看下接口說明:
/**
* <p>
* 查詢列表
* </p>
*
* @param queryWrapper 實(shí)體對(duì)象封裝操作類
* {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
List<T> list(Wrapper<T> queryWrapper);
/**
* <p>
* 根據(jù) ID 查詢
* </p>
*
* @param id 主鍵ID
*/
T getById(Serializable id);
/**
* <p>
* 根據(jù) Wrapper,查詢一條記錄
* </p>
*
* @param queryWrapper 實(shí)體對(duì)象封裝操作類
* {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
T getOne(Wrapper<T> queryWrapper);嗯,差不多了吧,這樣需要注意這樣一個(gè)方法:
/**
* <p>
* 從list中取第一條數(shù)據(jù)返回對(duì)應(yīng)List中泛型的單個(gè)結(jié)果
* </p>
*
* @param list
* @param <E>
* @return
*/
public static <E> E getObject(List<E> list) {
if (CollectionUtils.isNotEmpty(list)) {
int size = list.size();
if (size > 1) {
SqlHelper.logger.warn(
String.format("Warn: execute Method There are %s results.", size));
}
return list.get(0);
}
return null;
}下面說下分頁的問題
根據(jù)官網(wǎng)的說法,需要借助插件,這我們是可以理解。
在Spring Boot啟動(dòng)類里面添加:
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}這樣就可以使用他提供的分頁接口了:
/**
* <p>
* 翻頁查詢
* </p>
*
* @param page 翻頁對(duì)象
* @param queryWrapper 實(shí)體對(duì)象封裝操作類
* {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
*/
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
我們?nèi)タ匆幌拢?/p>
@Override
public IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper) {
queryWrapper = (Wrapper<T>) SqlHelper.fillWrapper(page, queryWrapper);
return baseMapper.selectPage(page, queryWrapper);
}
/**
* <p>
* 填充Wrapper
* </p>
*
* @param page 分頁對(duì)象
* @param wrapper SQL包裝對(duì)象
*/
@SuppressWarnings("unchecked")
public static Wrapper<?> fillWrapper(IPage<?> page, Wrapper<?> wrapper) {
if (null == page) {
return wrapper;
}
if (ArrayUtils.isEmpty(page.ascs())
&& ArrayUtils.isEmpty(page.descs())
&& ObjectUtils.isEmpty(page.condition())) {
return wrapper;
}
QueryWrapper qw;
if (null == wrapper) {
qw = new QueryWrapper<>();
} else {
qw = (QueryWrapper) wrapper;
}
// 排序
if (ArrayUtils.isNotEmpty(page.ascs())) {
qw.orderByAsc(page.ascs());
}
if (ArrayUtils.isNotEmpty(page.descs())) {
qw.orderByDesc(page.descs());
}
// MAP 參數(shù)查詢
if (ObjectUtils.isNotEmpty(page.condition())) {
qw.allEq(page.condition());
}
return qw;
}
/**
* <p>
* 根據(jù) entity 條件,查詢?nèi)坑涗洠ú⒎摚?
* </p>
*
* @param page 分頁查詢條件(可以為 RowBounds.DEFAULT)
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);分頁的代碼大抵就是這樣,我之前也自己寫過,思路還是相當(dāng)來說比較簡單,關(guān)鍵是看你的查詢添加如何封裝,分頁類如何構(gòu)造。
這里有一點(diǎn)說明:
分頁從 1 開始 !!!
枚舉類
1、實(shí)現(xiàn) 接口
/**
* <p>
* 自定義枚舉接口
* </p>
*
* @author hubin
* @since 2017-10-11
*/
public interface IEnum<T extends Serializable> {
/**
* 枚舉數(shù)據(jù)庫存儲(chǔ)值
*/
T getValue();
}2、實(shí)現(xiàn)注意
@Override
public Integer getValue() {
return this.value;
}
@JsonValue
public String getDesc() {
return desc;
}這是Jackson的寫法,我沒用FastJson,所以用的伙伴,去官網(wǎng)看一下:FastJson看官網(wǎng)。
3:被忘了在配置文件中添加掃描:
mybatis-plus: # 掃描枚舉類 # 支持統(tǒng)配符 * 或者 ; 分割 type-enums-package: com.fengwenyi.mp3demo.enums
差不多了吧,好像
邏輯刪除
1、代碼生成器中配置:
new StrategyConfig().setLogicDeleteFieldName("is_delete") // 邏輯刪除屬性名稱
或者,你可以手寫,參考:
@ApiModelProperty(value = "是否邏輯刪除(true:刪除;false:正常(默認(rèn)))")
@TableLogic
private Boolean isDelete;
2、自定義數(shù)據(jù)庫的值:
mybatis-plus:
global-config:
db-config:
#邏輯刪除配置
logic-delete-value: 1
logic-not-delete-value: 0
MyBatis-Plus-Example
MyBatis-Plus的代碼都會(huì)上傳到github上
https://github.com/fengwenyi/MyBatis-Plus-Example
參考資料
MyBatis-Plus 使用枚舉自動(dòng)關(guān)聯(lián)注入
修復(fù)Long類型太長,而Java序列化JSON丟失精度問題的方法
總結(jié)
到此這篇關(guān)于MyBatis-Plus最優(yōu)雅最簡潔地完成數(shù)據(jù)庫操作的文章就介紹到這了,更多相關(guān)MyBatis-Plus數(shù)據(jù)庫操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java?SpringBoot整合shiro-spring-boot-starterqi項(xiàng)目報(bào)錯(cuò)解決
這篇文章主要介紹了Java?SpringBoot整合shiro-spring-boot-starterqi項(xiàng)目報(bào)錯(cuò)解決,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考一下2022-08-08
Java導(dǎo)出Excel通用工具類實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于Java導(dǎo)出Excel通用工具類的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
java使用靜態(tài)關(guān)鍵字實(shí)現(xiàn)單例模式
這篇文章主要為大家詳細(xì)介紹了java使用靜態(tài)關(guān)鍵字實(shí)現(xiàn)單例模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
解決nacos項(xiàng)目啟動(dòng)報(bào)錯(cuò):Connection refused: no further&
這篇文章主要介紹了解決nacos項(xiàng)目啟動(dòng)報(bào)錯(cuò):Connection refused: no further informa問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
spring boot高并發(fā)下耗時(shí)操作的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于spring boot高并發(fā)下耗時(shí)操作的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
mybatis如何獲取剛剛新插入數(shù)據(jù)的主鍵值id
這篇文章主要介紹了mybatis如何獲取剛剛新插入數(shù)據(jù)的主鍵值id問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08

