MyBatis-Plus插件機(jī)制及通用Service新功能
1.高級(jí)(插件機(jī)制)
1.1自動(dòng)填充
項(xiàng)目中經(jīng)常會(huì)遇到一些數(shù)據(jù),每次都使用相同的方式填充,例如記錄的創(chuàng)建時(shí)間,更新時(shí)間等。
我們可以使用MyBatis Plus的自動(dòng)填充功能,完成這些字段的賦值工作:
1.1.1 原理
- 實(shí)現(xiàn)元對(duì)象處理器接口:
com.baomidou.mybatisplus.core.handlers.MetaObjectHandler,確定填充具體操作 - 注解填充字段:
@TableField(fill = ...)確定字段填充的時(shí)機(jī) - 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;
}步驟三:編寫(xiě)處理類(lèi)

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);
}
}步驟四:測(cè)試
@Test
public void testInsert() {
Customer customer = new Customer();
customer.setCname("測(cè)試888");
customerMapper.insert(customer);
}
@Test
public void testUpdate() {
Customer customer = new Customer();
customer.setCid(11);
customer.setTelephone("999");
customerMapper.updateById(customer);
}1.2樂(lè)觀鎖
- 基于數(shù)據(jù)庫(kù)
- 樂(lè)觀鎖:數(shù)據(jù)不同步
不會(huì)發(fā)生。讀鎖。 - 悲觀鎖:數(shù)據(jù)不同步
肯定發(fā)生。寫(xiě)鎖。
1.2.1 什么是樂(lè)觀鎖
- 目的:數(shù)據(jù)必須同步。當(dāng)要更新一條記錄的時(shí)候,希望這條記錄沒(méi)有被別人更新
- 樂(lè)觀鎖實(shí)現(xiàn)方式:
取出記錄時(shí),獲取當(dāng)前version
更新時(shí),帶上這個(gè)version
執(zhí)行更新時(shí), set version = newVersion where version = oldVersion
如果version不對(duì),就更新失敗
1.2.2. 實(shí)現(xiàn)
步驟:
- 步驟1:環(huán)境準(zhǔn)備(表version字段、JavaBean versoin屬性、必須提供默認(rèn)值)
- 步驟2:使用樂(lè)觀鎖版本控制 @Version
- 步驟3:開(kāi)啟樂(lè)觀鎖插件配置
- 步驟一:修改表結(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;
}- 步驟三:元對(duì)象處理器接口添加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 開(kāi)啟樂(lè)觀鎖
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();
// 分頁(yè)插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 樂(lè)觀鎖
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}- 步驟五:測(cè)試
- 先添加一條,保證version有數(shù)據(jù)
- 在更新該條
@Test
public void testUpdate() {
Customer customer = new Customer();
customer.setCid(14);
customer.setCname("測(cè)試999");
// 與數(shù)據(jù)庫(kù)中數(shù)據(jù)一致,將更新成功,否則返回失敗。
customer.setVersion(1);
int i = customerMapper.updateById(customer);
System.out.println(i);
}1.2.3 注意事項(xiàng)
支持的數(shù)據(jù)類(lèi)型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數(shù)類(lèi)型下
newVersion = oldVersion + 1
newVersion會(huì)回寫(xiě)到entity中僅支持
updateById(id)與update(entity, wrapper)方法在
update(entity, wrapper)方法下,wrapper不能復(fù)用!!!數(shù)據(jù)庫(kù)表的version字段,必須有默認(rèn)值(SQL語(yǔ)句默認(rèn)值、或MyBatisPlus自動(dòng)填充)
在進(jìn)行更新操作時(shí),必須設(shè)置version值,否則無(wú)效。
1.3邏輯刪除
1.3.1 什么是邏輯刪除
邏輯刪除,也稱(chēng)為假刪除。就是在表中提供一個(gè)字段用于記錄是否刪除,實(shí)際該數(shù)據(jù)沒(méi)有被刪除。
1.3.2 實(shí)現(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í),設(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);
}
}步驟四:測(cè)試
@Test
public void testDelete() {
// 刪除時(shí),必須保證deleted數(shù)據(jù)為“邏輯未刪除值”
int i = customerMapper.deleteById(12);
System.out.println(i);
}1.3.3 注意
- 如果使用邏輯刪除,將delete語(yǔ)句,修改成了update,條件 where deleted=0
- 同時(shí),查詢(xún)語(yǔ)句自動(dòng)追加一個(gè)查詢(xún)條件
WHERE deleted=0。如果查詢(xún)沒(méi)有數(shù)據(jù),檢查deleted字段的值。
1.3.4 全局配置
如果使用了全局配置,可以不使用注解@TableLogic
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted # 局邏輯刪除的實(shí)體字段名
logic-delete-value: 1 # 邏輯已刪除值(默認(rèn)為 1)
logic-not-delete-value: 0 # 邏輯未刪除值(默認(rèn)為 0)1.3.5 恢復(fù)
- 問(wèn)題:進(jìn)行邏輯刪除后的數(shù)據(jù),如何恢復(fù)(recovery)?
- 方案1:使用sql具有,更新deleted=0即可
UPDATE `tmp_customer` SET `deleted`='0' WHERE `cid`='13';
方案2:直接使用update語(yǔ)句,==不能==解決問(wèn)題。
@Test
public void testUpdate() {
Customer customer = new Customer();
customer.setCid(13);
customer.setDeleted(0);
//更新
customerMapper.updateById(customer);
}方案3:修改Mapper,添加 recoveryById 方法,進(jìn)行數(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:接口 + 實(shí)現(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實(shí)現(xiàn)類(lèi)
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常見(jiàn)方法
- 查詢(xún)所有
- 添加
- 修改
- 刪除
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分析打印
該功能依賴(lài)
p6spy組件,完美的輸出打印 SQL 及執(zhí)行時(shí)長(zhǎng)
p6spy 依賴(lài)引入
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>核心yml配置
spring:
datasource:
# p6spy 提供的驅(qū)動(dòng)代理類(lèi),
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
# url 固定前綴為 jdbc:p6spy,跟著冒號(hào)為對(duì)應(yīng)數(shù)據(jù)庫(kù)連接地址
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 #日志輸出到控制臺(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 # 是否開(kāi)啟慢SQL記錄 outagedetection=true # 慢SQL記錄標(biāo)準(zhǔn) 2 秒 outagedetectioninterval=2
3.2數(shù)據(jù)庫(kù)安全保護(hù)
為了保護(hù)數(shù)據(jù)庫(kù)配置及數(shù)據(jù)安全,在一定的程度上控制開(kāi)發(fā)人員流動(dòng)導(dǎo)致敏感信息泄露
- 步驟:
- 步驟1:使用 AES 工具類(lèi),
生成秘鑰。 - 步驟2:使用 AES工具類(lèi),根據(jù)步驟1生成的秘鑰對(duì)敏感信息
進(jìn)行加密 - 步驟3:設(shè)置加密后的
配置信息 - 步驟4:?jiǎn)?dòng)服務(wù)時(shí),
使用秘鑰
步驟1-2:使用工具類(lèi)生成秘鑰以及對(duì)敏感信息進(jìn)行加密
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 啟動(dòng)參數(shù)( idea 設(shè)置 Program arguments , 服務(wù)器可以設(shè)置為啟動(dòng)環(huán)境變量 )
//--mpw.key=fddd2b7a67460e16
//mpw:7kSEISvq3QWfnSh6vQZc2xgE+XF/sJ0WS/sgGkYpCOTQRjO1poLi3gfmGZNOwKzfqZUec0odiwAdmxcS7lfueENGIx8OmIe//d9imrGFpnkrf8jNSHdzfNPCUi3MbmUb
//mpw:qGbCMksqA90jjiGXXRr7lA==
//mpw:xKG9GABlywqar6CGPOSJKQ==步驟3:配置加密信息

步驟4:使用秘鑰啟動(dòng)服務(wù)

到此這篇關(guān)于MyBatis-Plus插件機(jī)制以及通用Service、新功能的文章就介紹到這了,更多相關(guān)MyBatis-Plus插件通用Service內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Mybatis-plus的service通用接口解讀
- Mybatis-plus中IService接口的基本使用步驟
- Mybatis-Plus接口BaseMapper與Services使用詳解
- Mybatis-Plus實(shí)體類(lèi)注解方法與mapper層和service層的CRUD方法
- 詳解關(guān)于mybatis-plus中Service和Mapper的分析
- mybatis-plus批處理IService的實(shí)現(xiàn)示例
- MyBatis-Plus 通用IService使用詳解
- mybatisplus中返回Vo的案例講解
- mybatis-plus 自定義 Service Vo接口實(shí)現(xiàn)數(shù)據(jù)庫(kù)實(shí)體與 vo 對(duì)象轉(zhuǎn)換返回功能
相關(guān)文章
Spring Boot整合FTPClient線程池的實(shí)現(xiàn)示例
這篇文章主要介紹了Spring Boot整合FTPClient線程池的實(shí)現(xiàn)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
解決IntelliJ IDEA中鼠標(biāo)拖動(dòng)選擇為矩形區(qū)域問(wèn)題
這篇文章主要介紹了解決IntelliJ IDEA中鼠標(biāo)拖動(dòng)選擇為矩形區(qū)域問(wèn)題,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
項(xiàng)目打包成jar后包無(wú)法讀取src/main/resources下文件的解決
本文主要介紹了項(xiàng)目打包成jar后包無(wú)法讀取src/main/resources下文件的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無(wú)刷新上傳
這篇文章主要介紹了SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無(wú)刷新上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10

