日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

mybatis-plus (3.4.2)使用

發布時間:2025/3/11 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mybatis-plus (3.4.2)使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

快速入門

官方文檔快速入門案例

配置日志

# 配置日志mybatis-plus:configuration:# 配置 mybatis-plus執行的日志類型(可以看到執行過程) 下面是使用了控制臺輸出 sl4j log4j 等等都可以log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

效果

CRUD擴展

數據庫中未指定id自增方式 我們可以通過mybatis-plus 來生成

插入一條數據

User user = new User(); user.setAge(3); user.setName("xiuyuan"); user.setEmail("155645xxxx@qq.com");userMapper.insert(user);System.out.println(user);

你會發現,我們雖然沒有指定id,但是他會自動給我們生成id,并賦給了user

數據庫插入的id的默認值為:全局的唯一id

主鍵生成策略

分布式系統唯一Id生成方案匯總

Twitter的snowflake(雪花)算法

snowflake是Twitter開源的分布式ID生成算法,結果是一個long型的ID。其核心思想是:使用41bit作為毫秒數,10bit作為機器的ID(5個bit是數據中心,5個bit的機器ID),12bit作為毫秒內的流水號(意味著每個節點在每毫秒可以產生 4096 個 ID),最后還有一個符號位,永遠是0。具體實現的代碼可以參看https://github.com/twitter/snowflake。

mybatis-plus 默認主鍵生成方案 ID_WORKER

我們可以通過 @TableId 指定主鍵生成方式

public class User {@TableId(type = IdType.ID_WORKER)private Long id;private String name;private Integer age;private String email;

IdType

public enum IdType {AUTO(0), // 數據庫id自增NONE(1), // 未設置主鍵INPUT(2), //手動輸入ID_WORKER(3), // 默認的全局唯一idUUID(4), // 全局唯一id uuidID_WORKER_STR(5); // ID_WORKER 字符串表示法private int key;private IdType(int key) {this.key = key;}public int getKey() {return this.key;} }

更新操作

@Testvoid update(){User user = new User();user.setId(2L);user.setAge(20);// 自動支持 動態sql(會自動判斷 屬性是否為''或null)int i = userMapper.updateById(user);}



從更新操作中 你會發現它是支持動態sql判斷的(填充動態sql)。

自動填充

創建時間和修改時間!這些操作一般都是自動化完成的,我們不希望手動更新!

方式一 數據庫級別(工作中不推薦)

方式二 代碼級別

自動填充功能入門

1、實體類上添加填充注解

// 字段添加填充內容@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;

2、編寫一個處理器來處理注解

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 {// 插入時填充的操作@Overridepublic void insertFill(MetaObject metaObject) {// 方法簽名 MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}// 更新時填充的操作@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime",new Date(),metaObject);} }

測試一下

樂觀鎖

mybaits-plus樂觀鎖官方文檔

當要更新一條記錄的時候,希望這條記錄沒有被別人更新
樂觀鎖實現方式:

  • 取出記錄時,獲取當前version
  • 更新時,帶上這個version
  • 執行更新時, set version = newVersion where version = oldVersion
  • 如果version不對,就更新失敗

1、給數據庫中增加version字段

2、我們的實體類同步字段

// mybatis-plus 的樂觀鎖 Version注解 @Version private Integer version;

@Version 說明:

支持的數據類型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數類型下 newVersion = oldVersion + 1
newVersion 會回寫到 entity 中
僅支持 updateById(id) 與 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能復用!!!

3、配置樂觀鎖插件(新版本已失效)

新版本已失效

@MapperScan("com.zlf.mapper") @Configuration public class mybatisPlusConfig {@Beanpublic OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor(){return new OptimisticLockerInnerInterceptor();} }

新版本

@MapperScan("com.zlf.mapper") @Configuration public class mybatisPlusConfig {/*** 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題(該屬性會在舊插件移除后一同移除)*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 分頁插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));// 配置 樂觀鎖攔截器OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);return interceptor;}@Beanpublic ConfigurationCustomizer configurationCustomizer() {return configuration -> configuration.setUseDeprecatedExecutor(false);} }

測試

/*** 測試樂觀鎖失敗(模擬多線程)*/@Testvoid testLock2(){// 1、查詢用戶信息User user = userMapper.selectById(1L);// 2、修改用戶信息user.setEmail("cccc@abc");user.setAge(18);User user2 = userMapper.selectById(1L);user.setName("小白");// 插隊修改userMapper.updateById(user2);userMapper.updateById(user);}


查詢操作

基礎查詢

/*** 測試查詢*/@Testvoid testSelect(){// 查詢一個User user = userMapper.selectById(1L);// 查詢多個 方法簽名 List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);List<User> users = userMapper.selectBatchIds(Arrays.asList(1L,2L,3L));// 條件查詢之一 selectByMapHashMap<String, Object> map = new HashMap<>();map.put("name","小白"); // key 是列名 value 是要查詢的值map.put("age",18); // 多個條件之間是 andList<User> users1 = userMapper.selectByMap(map);}

分頁查詢

1、配置分頁攔截器

/*** 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題(該屬性會在舊插件移除后一同移除)*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//分頁攔截器interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));// 配置 樂觀鎖攔截器OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);return interceptor;}

2、直接使用Page對象

@Testvoid testPage(){// 參數一:當前頁,參數二:顯示條數Page<User> page = new Page<>(1,5);// 分頁查詢Page<User> userPage = userMapper.selectPage(page, null);// 獲取記錄 getRecords()userPage.getRecords().forEach(System.out::println);}

測試結果

刪除操作

@Testvoid testDelete(){// 通過id刪除一條記錄userMapper.deleteById(1L);// 通過id集合刪除整個集合對應記錄userMapper.deleteBatchIds(Arrays.asList(2L,3L));// 通過條件刪除 條件之間為 andMap<String, Object> map = new HashMap<>();map.put("name","小黑");map.put("age",18);userMapper.deleteByMap(map);}

邏輯刪除

邏輯刪除官方文檔

物理刪除:從數據庫中直接移除
邏輯刪除:在數據庫中沒有被移除,而是通過一個變量來讓他失效!

類似管理員查看被刪除的記錄。防止數據的丟失,類似于回收站!

1、在數據表中添加一個字段deleted

2、在實體類中添加屬性

@TableLogic //邏輯刪除注解private Integer deleted;

3、配置

mybatis-plus:global-config:db-config:# 配置邏輯刪除logic-delete-field: deleted # 全局邏輯刪除的實體字段名(since 3.3.0,配置后可以忽略@TableLogic)logic-delete-value: 1 # 邏輯已刪除值(默認為 1)logic-not-delete-value: 0 # 邏輯未刪除值(默認為 0)

測試

@Testvoid testDelete(){// 通過id刪除一條記錄userMapper.deleteById(2L);}

你會發現 刪除變成了更新deleted 的值了

數據庫中

我們再來查詢一下

@Testvoid testLock(){// 1、查詢用戶信息User user = userMapper.selectById(2L);System.out.println(user);}

已經查不到了 sql中會過濾 deleted=0 的

性能分析插件

舊版本就不說了。
新版本在 執行 SQL 分析打印官方文檔

條件構造器

條件構造器官方文檔

代碼自動生成器

這邊使用的版本是3.4.1

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.4.1</version> </dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version> </dependency>

代碼生成器官方文檔

import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;import java.util.ArrayList;@SpringBootTest class MallApplicationTests {@Testvoid contextLoads() {}@Testpublic void run() {// 1、創建代碼生成器AutoGenerator mpg = new AutoGenerator();// 2、全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("zlf");gc.setOpen(false); //生成后是否打開資源管理器gc.setFileOverride(false); //重新生成時文件是否覆蓋gc.setServiceName("%sService"); //去掉Service接口的首字母Igc.setIdType(IdType.ID_WORKER); //主鍵策略gc.setDateType(DateType.ONLY_DATE);//定義生成的實體類中日期類型gc.setSwagger2(true);//開啟Swagger2模式mpg.setGlobalConfig(gc);// 3、數據源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/數據庫名");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("xxxx");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);// 4、包配置PackageConfig pc = new PackageConfig();pc.setModuleName("mall"); //模塊名pc.setParent("com");// com.zlf.edu.controllerpc.setController("controller");pc.setEntity("entity");pc.setService("service");pc.setMapper("mapper");mpg.setPackageInfo(pc);// 5、策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("表名");strategy.setNaming(NamingStrategy.underline_to_camel);//數據庫表映射到實體的命名策略strategy.setTablePrefix(pc.getModuleName() + "_"); //生成實體時去掉表前綴strategy.setColumnNaming(NamingStrategy.underline_to_camel);//數據庫表字段映射到實體的命名策略strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter鏈式操作strategy.setRestControllerStyle(true); //restful api風格控制器strategy.setControllerMappingHyphenStyle(true); //url中駝峰轉連字符strategy.setLogicDeleteFieldName("is_deleted");// 自動填充配置TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE);ArrayList<TableFill> tableFills = new ArrayList<>();tableFills.add(gmtCreate);tableFills.add(gmtModified);strategy.setTableFillList(tableFills);mpg.setStrategy(strategy);// 6、執行mpg.execute();}}

推薦B站Up狂神

良心up主,強烈推薦!!

總結

以上是生活随笔為你收集整理的mybatis-plus (3.4.2)使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。