MyBatis-Plus邏輯刪除和字段自動(dòng)填充的實(shí)現(xiàn)
一、ID生成策略
1、使用@TableId注解
@TableId注解:主鍵注解
使用位置:實(shí)體類主鍵字段。
@Data @ToString @TableName("t_user") public class UserDO { @TableId(value = "id", type = IdType.AUTO) private Long id; ... }
2、全局ID生成策略
使用注解是針對(duì)一個(gè)POJO的。如果我們?nèi)质褂猛瑯拥?ID生成策略。那我們可以在全局配置文件中配置。就不需要在每個(gè) POJO上使用 主鍵@TableId注解了。
mybatis-plus: global-config: db-config: id-type: auto
二、邏輯刪除
官方文檔-邏輯刪除:https://baomidou.com/pages/6b03c5/
邏輯刪除: 通常會(huì)在表里添加一個(gè)邏輯刪除的字段,比如 enabled(1默認(rèn)有效,0無效)。
MyBatis-Plus會(huì)在用戶調(diào)用刪除操作時(shí)將數(shù)據(jù)修改 UPDATE set enabled = 0, 在查詢的時(shí)候會(huì)自動(dòng)拼接只查 where enabled=1的數(shù)據(jù)。
1、全局配置
在YAML配置文件中添加全局配置
mybatis-plus: global-config: db-config: logic-delete-field: flag # 全局邏輯刪除的實(shí)體字段名(since 3.3.0,配置后可以忽略不配置步驟2) logic-delete-value: 1 # 邏輯已刪除值(默認(rèn)為 1) logic-not-delete-value: 0 # 邏輯未刪除值(默認(rèn)為 0)
不推薦使用全局配置,使用 @TableLogic注解
見名知意。
2、使用@TableLogic注解
@TableLogic注解:表字段邏輯處理注解(邏輯刪除)。
1)表中添加 enabled字段
ALTER TABLE `t_user` ADD COLUMN `enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否有效(1-有效,0-無效)';
2)在POJO實(shí)體類字段上加上 @TableLogic注解。
/** * 代表邏輯刪除 * value:邏輯未刪除值 * delval:邏輯刪除值 */ //@TableLogic @TableLogic(value = "1", delval = "0") private Integer enabled;
到此,邏輯刪除就配置好了,接下來測(cè)試一下刪除和查詢。
@Test public void testRemoveById() { System.out.println(("----- removeById method test ------")); boolean remove = userService.removeById(12L); System.out.println("remove = " + remove); }
@Test public void testGetById() { System.out.println(("----- getById method test ------")); UserDO userDO = userService.getById(12L); System.out.println("userDO = " + userDO); }
三、字段自動(dòng)填充
官方文檔-自動(dòng)填充功能:https://baomidou.com/pages/4c6bcf/
在項(xiàng)目中,一般我們都會(huì)定義 create_time和update_time字段。針對(duì)這兩個(gè)字段,每次CRUD操作時(shí),我們都需要手動(dòng)賦值或者數(shù)據(jù)庫默認(rèn)值。MyBatis-Plus提供了給字段自動(dòng)填充數(shù)據(jù)的功能。
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間',
使用 MyBatis-Plus的自動(dòng)填充功能,需要指定 fill類型,并且指定 自定義填充信息 MetaObjectHandler。
1、指定字段自動(dòng)填充
在POJO中,指定 create_time和update_time字段為自動(dòng)填充。
@TableField(value = "create_time", fill = FieldFill.INSERT) //@TableField(value = "create_time") private Date createTime; @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) //@TableField(value = "update_time") private Date updateTime;
fill類型的值如下:
注意:
如果指定了 fill為后面三個(gè)時(shí),必須顯示設(shè)置值。否則為報(bào)錯(cuò):Column 'create_time' cannot be null。如果我們不顯示指定設(shè)置值,我們必須定義 MetaObjectHandler。
2、自定義MetaObjectHandler
@Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { log.info("start insert fill ...."); /** *方法的四個(gè)個(gè)參數(shù):<br/> * MetaObject metaObject: metaObject對(duì)象 <br/> * String fieldName:POJO字段 <br/> * Class<T> fieldType:字段類型 <br/> * E fieldVal:自動(dòng)填充的字段值 <br/> */ this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); //this.setFieldValByName("createTime", new Date(),metaObject); // 或者 this.strictInsertFill(metaObject, "updateTime", () -> new Date(), Date.class); } @Override public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); this.strictInsertFill(metaObject, "updateTime", () -> new Date(), Date.class); } }
3、測(cè)試
1)測(cè)試保存
@Test public void testSave() { System.out.println(("----- save method test ------")); UserDO userDO = new UserDO(); userDO.setUserName("趙云save fill"); userDO.setAge(20); userDO.setHeight(1.88); userDO.setEmail("zhaoyun@123.com"); boolean save = userService.save(userDO); System.out.println("save = " + save); System.out.println("userDO = " + userDO); }
2)測(cè)試刪除
@Test public void testRemoveById() { System.out.println(("----- removeById method test ------")); boolean remove = userService.removeById(111L); System.out.println("remove = " + remove); }
四、執(zhí)行SQL分析打印
生產(chǎn)環(huán)境不推薦使用,開發(fā)環(huán)境可以使用。
官方文檔-自動(dòng)填充功能:https://baomidou.com/pages/833fab/
引入 p6spy依賴:
<!-- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.9.1</version> </dependency>
1、添加 spy.properties配置文件
#3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory #3.2.1以下使用或者不配置 #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定義日志打印 logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger #日志輸出到控制臺(tái) appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger # 使用日志系統(tǒng)記錄 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 設(shè)置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前綴 useprefix=true # 配置記錄 Log 例外,可去掉的結(jié)果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 實(shí)際驅(qū)動(dòng)可多個(gè) #driverlist=org.h2.Driver # 是否開啟慢SQL記錄 outagedetection=true # 慢SQL記錄標(biāo)準(zhǔn) 2 秒 outagedetectioninterval=2
2、修改數(shù)據(jù)源配置
修改驅(qū)動(dòng)類和 url的前綴。
spring: ## 數(shù)據(jù)源配置 datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver # com.mysql.cj.jdbc.Driver # url: jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT url: jdbc:p6spy:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT username: root password: 123456
3、測(cè)試查詢
多了紅色的部分,其實(shí)我們使用 MyBatisLogFormat插件也是可以得到真實(shí)執(zhí)行的SQL語句。
到此這篇關(guān)于MyBatis-Plus邏輯刪除和字段自動(dòng)填充的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Plus邏輯刪除和字段自動(dòng)填充內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MyBatisPlus實(shí)現(xiàn)自動(dòng)填充字段的實(shí)踐
- MyBatis-Plus自動(dòng)填充字段的詳細(xì)教程
- mybatis-plus調(diào)用update方法時(shí),自動(dòng)填充字段不生效問題及解決
- MyBatis-Puls插入或修改時(shí)某些字段自動(dòng)填充操作示例
- Mybatis-Plus實(shí)現(xiàn)公共字段自動(dòng)填充的項(xiàng)目實(shí)踐
- MyBatis-Plus實(shí)現(xiàn)公共字段自動(dòng)填充功能詳解
- Mybatis-Plus自動(dòng)填充更新操作相關(guān)字段的實(shí)現(xiàn)
- MyBatis-Plus實(shí)現(xiàn)字段自動(dòng)填充功能的示例
- Mybatis plus通用字段自動(dòng)填充的示例
- Mybatis攔截器實(shí)現(xiàn)公共字段填充的示例代碼
相關(guān)文章
Java用list儲(chǔ)存,遍歷,查詢指定信息過程詳解
這篇文章主要介紹了Java用list儲(chǔ)存,遍歷,查詢指定信息過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10使用Mybatis對(duì)數(shù)據(jù)庫進(jìn)行單表操作的實(shí)現(xiàn)示例
這篇文章主要介紹了使用Mybatis對(duì)數(shù)據(jù)庫進(jìn)行單表操作的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Java詳細(xì)講解堆排序與時(shí)間復(fù)雜度的概念
本文主要介紹了java實(shí)現(xiàn)堆排序以及時(shí)間復(fù)雜度,堆排序這種排序算法是我們經(jīng)常用到的,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04SpringBoot詳解整合Spring?Boot?Admin實(shí)現(xiàn)監(jiān)控功能
這篇文章主要介紹了SpringBoot整合Spring?Boot?Admin實(shí)現(xiàn)服務(wù)監(jiān)控,內(nèi)容包括Server端服務(wù)開發(fā),Client端服務(wù)開發(fā)其中Spring?Boot?Admin還可以對(duì)其監(jiān)控的服務(wù)提供告警功能,如服務(wù)宕機(jī)時(shí),可以及時(shí)以郵件方式通知運(yùn)維人員,感興趣的朋友跟隨小編一起看看吧2022-07-07Java中LocalDate日期格式轉(zhuǎn)換(使用系統(tǒng)時(shí)區(qū))
本文主要介紹了Java中LocalDate日期格式轉(zhuǎn)換(使用系統(tǒng)時(shí)區(qū)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2007-02-02