MyBatis-Plus插件機制及通用Service新功能
1.高級(插件機制)
1.1自動填充
項目中經(jīng)常會遇到一些數(shù)據(jù),每次都使用相同的方式填充,例如記錄的創(chuàng)建時間,更新時間等。
我們可以使用MyBatis Plus的自動填充功能,完成這些字段的賦值工作:
1.1.1 原理
- 實現(xiàn)元對象處理器接口:
com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
,確定填充具體操作 - 注解填充字段:
@TableField(fill = ...)
確定字段填充的時機 - FieldFill.INSERT:插入填充字段
- FieldFill.UPDATE:更新填充字段
- FieldFill.INSERT_UPDATE:插入和更新填充字段
1.1.2 基本操作
步驟一:修改表添加字段
alter table tmp_customer add column create_time date; alter table tmp_customer add column update_time date;
步驟二:修改JavaBean
package com.czxy.mp.domain; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.util.Date; /** * Created by liangtong. */ @Data @TableName("tmp_customer") public class Customer { @TableId(type = IdType.AUTO) private Integer cid; private String cname; private String password; private String telephone; private String money; @TableField(value="create_time",fill = FieldFill.INSERT) private Date createTime; @TableField(value="update_time",fill = FieldFill.UPDATE) private Date updateTime; }
步驟三:編寫處理類
package com.czxy.mp.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; @Component public class MyMetaObjectHandler implements MetaObjectHandler { /** * 插入填充 * @param metaObject */ @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); } /** * 更新填充 * @param metaObject */ @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); } }
步驟四:測試
@Test public void testInsert() { Customer customer = new Customer(); customer.setCname("測試888"); customerMapper.insert(customer); } @Test public void testUpdate() { Customer customer = new Customer(); customer.setCid(11); customer.setTelephone("999"); customerMapper.updateById(customer); }
1.2樂觀鎖
- 基于數(shù)據(jù)庫
- 樂觀鎖:數(shù)據(jù)不同步
不會
發(fā)生。讀鎖。 - 悲觀鎖:數(shù)據(jù)不同步
肯定
發(fā)生。寫鎖。
1.2.1 什么是樂觀鎖
- 目的:數(shù)據(jù)必須同步。當(dāng)要更新一條記錄的時候,希望這條記錄沒有被別人更新
- 樂觀鎖實現(xiàn)方式:
取出記錄時,獲取當(dāng)前version
更新時,帶上這個version
執(zhí)行更新時, set version = newVersion where version = oldVersion
如果version不對,就更新失敗
1.2.2. 實現(xiàn)
步驟:
- 步驟1:環(huán)境準(zhǔn)備(表version字段、JavaBean versoin屬性、必須提供默認(rèn)值)
- 步驟2:使用樂觀鎖版本控制 @Version
- 步驟3:開啟樂觀鎖插件配置
- 步驟一:修改表結(jié)構(gòu),添加version字段
- 步驟二:修改JavaBean,添加version屬性
package com.czxy.mp.domain; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; /** * Created by liangtong. */ @Data @TableName("tmp_customer") public class Customer { @TableId(type = IdType.AUTO) private Integer cid; private String cname; private String password; private String telephone; private String money; @Version @TableField(fill = FieldFill.INSERT) private Integer version; }
- 步驟三:元對象處理器接口添加version的insert默認(rèn)值 (保證version有數(shù)據(jù))
package com.czxy.mp.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; /** * Created by liangtong. */ @Component public class MyMetaObjectHandler implements MetaObjectHandler { /** * 插入填充 * @param metaObject */ @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("version", 1, metaObject); } /** * 更新填充 * @param metaObject */ @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); } }
步驟四:修改 MybatisPlusConfig 開啟樂觀鎖
package com.czxy.mp.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by liangtong. */ @Configuration public class MybatisPlusConfig { */ /** * 配置插件 * @return */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); // 分頁插件 mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 樂觀鎖 mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mybatisPlusInterceptor; } }
- 步驟五:測試
- 先添加一條,保證version有數(shù)據(jù)
- 在更新該條
@Test public void testUpdate() { Customer customer = new Customer(); customer.setCid(14); customer.setCname("測試999"); // 與數(shù)據(jù)庫中數(shù)據(jù)一致,將更新成功,否則返回失敗。 customer.setVersion(1); int i = customerMapper.updateById(customer); System.out.println(i); }
1.2.3 注意事項
支持的數(shù)據(jù)類型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數(shù)類型下
newVersion = oldVersion + 1
newVersion
會回寫到entity
中僅支持
updateById(id)
與update(entity, wrapper)
方法在
update(entity, wrapper)
方法下,wrapper
不能復(fù)用!!!數(shù)據(jù)庫表的version字段,必須有默認(rèn)值(SQL語句默認(rèn)值、或MyBatisPlus自動填充)
在進行更新操作時,必須設(shè)置version值,否則無效。
1.3邏輯刪除
1.3.1 什么是邏輯刪除
邏輯刪除,也稱為假刪除。就是在表中提供一個字段用于記錄是否刪除,實際該數(shù)據(jù)沒有被刪除。
1.3.2 實現(xiàn)
步驟:
步驟一:環(huán)境(表提供字段deleted、JavaBean屬性 deleted、填充默認(rèn)值0)
步驟二:修改JavaBean,添加注解 @TableLogic
步驟一:修改表結(jié)構(gòu)添加deleted字段
步驟二:修改JavaBean,給deleted字段添加@TableLogic
package com.czxy.mp.domain; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; /** * Created by liangtong. */ @Data @TableName("tmp_customer") public class Customer { @TableId(type = IdType.AUTO) private Integer cid; private String cname; private String password; private String telephone; private String money; @Version @TableField(fill = FieldFill.INSERT) private Integer version; @TableLogic @TableField(fill = FieldFill.INSERT) private Integer deleted; }
步驟三:添加數(shù)據(jù)時,設(shè)置默認(rèn)“邏輯未刪除值”
package com.czxy.mp.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; /** * Created by liangtong. */ @Component public class MyMetaObjectHandler implements MetaObjectHandler { /** * 插入填充 * @param metaObject */ @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("version", 1, metaObject); this.setFieldValByName("deleted", 0, metaObject); } /** * 更新填充 * @param metaObject */ @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); } }
步驟四:測試
@Test public void testDelete() { // 刪除時,必須保證deleted數(shù)據(jù)為“邏輯未刪除值” int i = customerMapper.deleteById(12); System.out.println(i); }
1.3.3 注意
- 如果使用邏輯刪除,將delete語句,修改成了update,條件 where deleted=0
- 同時,查詢語句自動追加一個查詢條件
WHERE deleted=0
。如果查詢沒有數(shù)據(jù),檢查deleted字段的值。
1.3.4 全局配置
如果使用了全局配置,可以不使用注解@TableLogic
mybatis-plus: global-config: db-config: logic-delete-field: deleted # 局邏輯刪除的實體字段名 logic-delete-value: 1 # 邏輯已刪除值(默認(rèn)為 1) logic-not-delete-value: 0 # 邏輯未刪除值(默認(rèn)為 0)
1.3.5 恢復(fù)
- 問題:進行邏輯刪除后的數(shù)據(jù),如何恢復(fù)(recovery)?
- 方案1:使用sql具有,更新deleted=0即可
UPDATE `tmp_customer` SET `deleted`='0' WHERE `cid`='13';
方案2:直接使用update語句,==不能==解決問題。
@Test public void testUpdate() { Customer customer = new Customer(); customer.setCid(13); customer.setDeleted(0); //更新 customerMapper.updateById(customer); }
方案3:修改Mapper,添加 recoveryById 方法,進行數(shù)據(jù)恢復(fù)。
@Mapper public interface CustomerMapper extends BaseMapper<Customer> { @Update("update tmp_customer set deleted = 0 where cid = #{cid}") public void recoveryById(@Param("cid") Integer cid); }
2.通用Service
2.1分析 通用Service分析
2.2基本使用 標(biāo)準(zhǔn)service:接口 + 實現(xiàn)
service接口
package com.czxy.service; import com.baomidou.mybatisplus.extension.service.IService; import com.czxy.domain.Customer; public interface CustomerService extends IService<Customer> { }
service實現(xiàn)類
package com.czxy.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.czxy.domain.Customer; import com.czxy.mapper.CustomerMapper; import com.czxy.service.CustomerService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class CustomerServiceImpl extends ServiceImpl<CustomerMapper,Customer> implements CustomerService { }
2.3常見方法
- 查詢所有
- 添加
- 修改
- 刪除
package com.czxy.test; import com.czxy.mp.Day62MybatisPlusApplication; import com.czxy.mp.domain.Customer; import com.czxy.mp.service.CustomerService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = Day62MybatisPlusApplication.class) public class TestDay62CustomerService { @Resource private CustomerService customerService; @Test public void testSelectList() { List<Customer> list = customerService.list(); list.forEach(System.out::println); } @Test public void testInsert() { Customer customer = new Customer(); customer.setCname("張三"); customer.setPassword("9999"); // 添加 customerService.save(customer); } @Test public void testUpdate() { Customer customer = new Customer(); customer.setCid(14); customer.setCname("777"); customer.setPassword("777"); customerService.updateById(customer); } @Test public void testSaveOrUpdate() { Customer customer = new Customer(); customer.setCid(15); customer.setCname("999"); customer.setPassword("99"); customerService.saveOrUpdate(customer); } @Test public void testDelete() { customerService.removeById(15); } }
3.新功能
3.1執(zhí)行SQL分析打印
該功能依賴
p6spy
組件,完美的輸出打印 SQL 及執(zhí)行時長
p6spy 依賴引入
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.9.1</version> </dependency>
核心yml配置
spring: datasource: # p6spy 提供的驅(qū)動代理類, driver-class-name: com.p6spy.engine.spy.P6SpyDriver # url 固定前綴為 jdbc:p6spy,跟著冒號為對應(yīng)數(shù)據(jù)庫連接地址 url: jdbc:p6spy:mysql://127.0.0.1:3306...
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 #日志輸出到控制臺 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 # 實際驅(qū)動可多個 #driverlist=org.h2.Driver # 是否開啟慢SQL記錄 outagedetection=true # 慢SQL記錄標(biāo)準(zhǔn) 2 秒 outagedetectioninterval=2
3.2數(shù)據(jù)庫安全保護
為了保護數(shù)據(jù)庫配置及數(shù)據(jù)安全,在一定的程度上控制開發(fā)人員流動導(dǎo)致敏感信息泄露
- 步驟:
- 步驟1:使用 AES 工具類,
生成秘鑰
。 - 步驟2:使用 AES工具類,根據(jù)步驟1生成的秘鑰對敏感信息
進行加密
- 步驟3:設(shè)置加密后的
配置信息
- 步驟4:啟動服務(wù)時,
使用秘鑰
步驟1-2:使用工具類生成秘鑰以及對敏感信息進行加密
package com.czxy; import com.baomidou.mybatisplus.core.toolkit.AES; import org.junit.Test; public class TestAES { @Test public void testAes() { String randomKey = AES.generateRandomKey(); String url = "jdbc:p6spy:mysql://127.0.0.1:3306/zx_edu_teacher?useUnicode=true&characterEncoding=utf8"; String username = "root"; String password = "1234"; String urlAES = AES.encrypt(url, randomKey); String usernameAES = AES.encrypt(username, randomKey); String passwordAES = AES.encrypt(password, randomKey); System.out.println("--mpw.key=" + randomKey); System.out.println("mpw:" + urlAES); System.out.println("mpw:" + usernameAES); System.out.println("mpw:" + passwordAES); } } // Jar 啟動參數(shù)( idea 設(shè)置 Program arguments , 服務(wù)器可以設(shè)置為啟動環(huán)境變量 ) //--mpw.key=fddd2b7a67460e16 //mpw:7kSEISvq3QWfnSh6vQZc2xgE+XF/sJ0WS/sgGkYpCOTQRjO1poLi3gfmGZNOwKzfqZUec0odiwAdmxcS7lfueENGIx8OmIe//d9imrGFpnkrf8jNSHdzfNPCUi3MbmUb //mpw:qGbCMksqA90jjiGXXRr7lA== //mpw:xKG9GABlywqar6CGPOSJKQ==
步驟3:配置加密信息
步驟4:使用秘鑰啟動服務(wù)
到此這篇關(guān)于MyBatis-Plus插件機制以及通用Service、新功能的文章就介紹到這了,更多相關(guān)MyBatis-Plus插件通用Service內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis-plus的service通用接口解讀
- Mybatis-plus中IService接口的基本使用步驟
- Mybatis-Plus接口BaseMapper與Services使用詳解
- Mybatis-Plus實體類注解方法與mapper層和service層的CRUD方法
- 詳解關(guān)于mybatis-plus中Service和Mapper的分析
- mybatis-plus批處理IService的實現(xiàn)示例
- MyBatis-Plus 通用IService使用詳解
- mybatisplus中返回Vo的案例講解
- mybatis-plus 自定義 Service Vo接口實現(xiàn)數(shù)據(jù)庫實體與 vo 對象轉(zhuǎn)換返回功能
相關(guān)文章
Spring Boot整合FTPClient線程池的實現(xiàn)示例
這篇文章主要介紹了Spring Boot整合FTPClient線程池的實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12解決IntelliJ IDEA中鼠標(biāo)拖動選擇為矩形區(qū)域問題
這篇文章主要介紹了解決IntelliJ IDEA中鼠標(biāo)拖動選擇為矩形區(qū)域問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10項目打包成jar后包無法讀取src/main/resources下文件的解決
本文主要介紹了項目打包成jar后包無法讀取src/main/resources下文件的解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04SpringMVC結(jié)合ajaxfileupload.js實現(xiàn)文件無刷新上傳
這篇文章主要介紹了SpringMVC結(jié)合ajaxfileupload.js實現(xiàn)文件無刷新上傳,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10