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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Mybatis 特别篇 Mybatis-plus入门教程

發布時間:2023/12/31 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Mybatis 特别篇 Mybatis-plus入门教程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

MybatisPuls學習

  • 前言
  • 一、MybatisPuls有什么特點
    • 支持數據庫
  • 二、使用步驟
    • 1.快速入門(官網案例)
    • 2. 配置日志輸出
    • 3. MybatisPlus中的雪花算法
    • 4. 自定義ID生成策略
    • 5. 自動填充
    • 6. 樂觀鎖
    • 7. 查詢
      • 基本查詢
      • 分頁查詢
    • 8. 刪除
      • 普通刪除
      • 邏輯刪除
    • ~~9. 性能分析插件(好像新版被移除了)~~
    • 9. 條件構造器
      • 判斷條件
      • 使用 like + notLike + likeRight
      • 子查詢
      • 降序查詢
    • 10. 代碼生成器
  • 總結


前言

學習之前,需要有SSM基礎比較好,Mybatis可以節省我們大量的sql代碼編寫的時間,尤其在簡單的sql語句中只需要調用一個方法即可完成增刪改查


![在這里插入圖片描述](https://img-blog.csdnimg.cn/e06f79d0c29b497dbde8c3575c3f56fb.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5aSq5oeC57yW56iL,size_20,color_FFFFFF,t_70,g_se,x_16)

正如官方所介紹為簡化開發而生

一、MybatisPuls有什么特點

特性

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向對象操作
  • 強大的 CRUD 操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
  • 支持 Lambda 形式調用:通過 Lambda 表達式,方便的編寫各類查詢條件,無需再擔心字段寫錯
  • 支持主鍵自動生成:支持多達 4 種主鍵策略(內含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式調用,實體類只需繼承 Model 類即可進行強大的 CRUD 操作
  • 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
    內置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用
    內置分頁插件:基于 MyBatis 物理分頁,開發者無需關心具體操作,配置好插件之后,寫分頁等同于普通 List 查詢
  • 分頁插件支持多種數據庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種數據庫
    內置性能分析插件:可輸出 SQL 語句以及其執行時間,建議開發測試時啟用該功能,能快速揪出慢查詢
  • 內置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規則,預防誤操作

支持數據庫

任何能使用 mybatis 進行 CRUD, 并且支持標準 SQL 的數據庫,具體支持情況如下,如果不在下列表查看分頁部分教程 PR 您的支持。

mysql,oracle,db2,h2,hsql,sqlite,postgresql,sqlserver,Phoenix,Gauss ,clickhouse,Sybase,OceanBase,Firebird,cubrid,goldilocks,csiidb

二、使用步驟

1.快速入門(官網案例)

參考地址

  • 創建數據庫和user表
  • DROP TABLE IF EXISTS user;CREATE TABLE user (id BIGINT(20) NOT NULL COMMENT '主鍵ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',age INT(11) NULL DEFAULT NULL COMMENT '年齡',email VARCHAR(50) NULL DEFAULT NULL COMMENT '郵箱',PRIMARY KEY (id) );DELETE FROM user;INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
  • 使用IDEA創建工程 官網默認用h2數據庫我們不需要進行導入
  • <!--數據庫驅動--> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId> </dependency> <!--mybatis-plus不用在導入mybatis了--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version> </dependency>
  • 配置數據源
  • spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  • 開始編碼
    • 傳統mybatis寫法依然支持不做介紹,可參考mybatis原生案例
    • 使用mybatis-plus (pojo->mapper接口->使用)我們可以看到都不需要配置xml文件
      創建User實體類
    @Data @AllArgsConstructor @NoArgsConstructor public class User {private Long id;private String name;private Integer age;private String email; }

    創建Mapper接口

    //在對應的Mapper上面是實現基本的接口BaseMapper @Repository public interface UserMapper extends BaseMapper<User> { //所有的crud的擦歐總已經編寫完畢了 }

    簡單看看baseMapper里面已經定義好啦非常多的接口

    入口文件增加注解掃描Mapper
    @MapperScan("cn.qileyun.mybatisplus.mapper")
    測試一下看看

    //繼承baseMapper所有可以使用它的所有方法,里面已經封裝好了基本crud代碼 @Autowired private UserMapper userMapper;@Test void contextLoads() {List<User> users = userMapper.selectList(null);users.forEach(System.out::println); }

    2. 配置日志輸出

    #配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

    3. MybatisPlus中的雪花算法

    User user = new User(); user.setName("我愛學編程"); user.setAge(3); user.setEmail("1541177517@qq.com"); int result = userMapper.insert(user);//幫我們自動生成id System.out.println(result); System.out.println(user);

    我們并沒有插入id,當是給我們生成一個全局唯一id,我們來探究一下

    4. 自定義ID生成策略

    在pojo類中定義id

    • AUTO 自增 數據庫id必須是自增的
    • UUID uuid全球唯一id
    • INPUT 手動輸入需要自己配置id
    • ID_WORKER_STR 數字->字符串
    • INONE 不使用id生成
    • ID_WORKER 默認全局唯一id 雪花算法
    @TableId(type = IdType.AUTO)//自增 數據庫id必須是自增的private Long id;

    5. 自動填充

  • 修改數據庫
  • 修改實體類
  • // 字段填充內容 @TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;
  • 編寫處理器
  • @Slf4j @Component//加入到ico容器中 public class MyMetaObjectHandler implements MetaObjectHandler {//插入時的填充策略@Overridepublic void insertFill(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);} }
  • 執行插入和修改
  • 6. 樂觀鎖

    • 樂觀鎖:顧名思義十分樂觀,它總是認為不會出現問題,無論干什么不去上鎖!如果出現了問題,在次更新值測試

    • 悲觀鎖:顧名思義十分悲觀,無論干什么都會上鎖!再去操作!

    • 取出記錄時,獲取當前version

    • 更新時,帶上version

    • 執行更新時,set version = newVersion where = version = oldVersion

    • 如果version不對,就更新失敗

    --A update user set name = "lala",version = version+1 where id=2 and version = 1 --B 如果現在B先搶占了線程,就會導致A修改失敗,因為version字段已經+1操作變成了2了 update user set name = "lala",version = version+1 where id=2 and version = 1

    使用樂觀鎖插件

  • 增加字段
  • 實體類添加字段
  • @Version private Integer version;
  • 注冊組件
  • //掃描我們的mapper文件夾 @MapperScan("cn.qileyun.mybatisplus.mapper") @EnableTransactionManagement @Configuration//配置類 public class MybatisPlusConfig {//注冊樂觀鎖插件 這個按照你的mybatis二選一/*** 舊版*/@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();}/*** 新版*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return mybatisPlusInterceptor;} }
  • 測試看看
  • // 測試成功的案例@Testpublic void testOptimisticLocker() {//1. 查詢用戶信息User user = userMapper.selectById(1L);//2.修改用戶信息user.setName("zengfeiixang");user.setEmail("1541177517@qq.com");//3. 執行更新操作userMapper.updateById(user);}// 測試失敗的案例@Testpublic void testOptimisticLocker2() {//1. 查詢用戶信息User user = userMapper.selectById(1L);//2.修改用戶信息user.setName("bbbbb");user.setEmail("1541177517@qq.com");//模擬另外一個線程執行插隊操作User user2 = userMapper.selectById(1L);user2.setName("aaaaaa");user2.setEmail("1541177517@qq.com");//3. 執行更新操作userMapper.updateById(user2);//執行成功userMapper.updateById(user);//更改失敗如果沒有樂觀鎖就會覆蓋插隊線程的值}

    7. 查詢

    基本查詢

    //測試查詢@Testpublic void testSelectById(){//查詢單個User user = userMapper.selectById(1L);System.out.println(user);}//測試批量查詢@Testpublic void testSelectByBatchId(){List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));users.forEach(System.out::println);}//條件查詢 map@Testpublic void testSelectByBatchIds(){HashMap<String, Object> map = new HashMap<>();//自定義查詢map.put("name","Tom");map.put("age",28);List<User> users = userMapper.selectByMap(map);users.forEach(System.out::println);}

    分頁查詢

    分頁在網站使用的十分之多
    1、原始的limit進行分頁
    2、pageHelper 第三方插件
    3、MP其實內置了分頁插件
    使用教程

  • 注冊插件
  • //分頁插件 @Bean public PaginationInterceptor paginationInterceptor() {PaginationInterceptor paginationInterceptor = new PaginationInterceptor();return paginationInterceptor; }/** * 新的分頁插件,一緩和二緩遵循mybatis的規則,需要設置 新版本好像用這個了沒有測試 MybatisConfiguration#useDeprecatedExecutor = false 避免緩存出現問題(該屬性會在舊插件移除后一同移除) */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));return interceptor; }
  • 測試一下
  • //測試分頁查詢 public void testPage(){//參數1 第一頁//參數2 一頁條目數量IPage<User> page = new Page<>(1,5);IPage<User> userIPage = userMapper.selectPage(page, null);userIPage.getRecords().forEach(System.out::println);System.out.println(page.getTotal());//總計 }

    8. 刪除

    普通刪除

    //測試刪除 @Test public void testDeleteById(){userMapper.deleteById(1468132628929495041L); }//批量刪除 @Test public void testDeleteBatchId(){userMapper.deleteBatchIds(Arrays.asList(1468132628929495041L,1468132628929495042L)); }//通過Map刪除 public void testDeleteMap(){HashMap<String, Object> map = new HashMap<>();map.put("name","lala");userMapper.deleteByMap(map); }

    邏輯刪除

    物理刪除:從數據庫中直接移除
    邏輯刪除:在數據庫中沒有移除,而是通過一個變量來讓他失效!delete =0 => delete=1
    可以把他看成一個回收站一樣,只是給他標識一個已經不存在了

  • 數據庫增加字段
    增加int類型的delete字段并且默認值為0

  • 實體類增加字段

  • @TableLogic private Integer deleted;
  • 編寫配置
  • mybatis-plus:global-config:db-config:logic-delete-field: flag # 全局邏輯刪除的實體字段名(since 3.3.0,配置后可以忽略不配置步驟2)logic-delete-value: 1 # 邏輯已刪除值(默認為 1)logic-not-delete-value: 0 # 邏輯未刪除值(默認為 0)
  • 注冊插件
  • //邏輯刪除 @Bean public ISqlInjector sqlInjector(){return new LogicSqlInjector(); }
  • 測試刪除代碼
    其實執行的不在是delete操作了而是更新了字段吧deleted = 1

    查詢看看可以看出已經自動加上了deleted = 0的條件,判斷是否被刪除過
  • 9. 性能分析插件(好像新版被移除了)

    MP提供了性能分析插件,如果超過這個時間就停止運行!

  • 導入插件
  • //sql執行效率插件@Bean@Profile({"dev","test"})//設置dev test環境開啟,保證我們的效率public PerformanceInterceptor performanceInterceptor(){PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();performanceInterceptor.setMaxTime(100);//設置sql執行的最大時間,如果超超過了就不執行performanceInterceptor.setFormat(true);//sql格式化return new PerformanceInterceptor();}
  • 配置spring為開發環境
  • spring:profiles:active: dev
  • 測試使用
    如果這個時間超過100ms就會報錯
  • 9. 條件構造器

    可以看出官方有非常多的條件

    判斷條件

    @Testvoid contextLoads() {//查詢name不為空的用戶,年齡大于等于12,并且郵箱不為空QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.isNotNull("name").isNotNull("email").ge("age",12);userMapper.selectList(wrapper).forEach(System.out::println);}@Testvoid test2(){//查詢名字lalaQueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("name","lala");//selectOne 查詢一個數據System.out.println(userMapper.selectOne(wrapper));}//查詢 10 到 20 歲的用戶數 @Test void test3(){QueryWrapper<User> wrapper=new QueryWrapper<>();wrapper.between("age",10,20); ?Integer count = userMapper.selectCount(wrapper);//查詢 10 到 20 歲的用戶的結果數 ?System.out.println(count); }

    使用 like + notLike + likeRight

    @Test void selectLike01(){QueryWrapper<User> wrapper=new QueryWrapper<>();wrapper.notLike("name","To") //名字不包含 To.like("name","o") //名字包含 o 的//左和右 左:%e 右:e% 兩邊:%e%//右查詢.likeRight("email","test"); ?List<Map<String, Object>> users = userMapper.selectMaps(wrapper);users.forEach(System.out::println); }

    子查詢

    @Test void selectLike02(){QueryWrapper<User> wrapper=new QueryWrapper<>();wrapper//一個SQL語句寫的子查詢.inSql("id","select id from user where age<20"); ?List<Object> users = userMapper.selectObjs(wrapper);users.forEach(System.out::println); }

    降序查詢

    @Test void selectLike03(){QueryWrapper<User> wrapper=new QueryWrapper<>();//降序排序wrapper.orderByDesc("id");//升序排序//wrapper.orderByAsc("id"); ?List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println); }

    更多的可以參考官方文檔

    10. 代碼生成器

  • 添加依賴
  • <!--代碼生成器--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.0.7</version> </dependency> <!--模版 --> <dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version> </dependency>
  • 測試類編寫生成代碼類
  • //需要構建一個代碼生成器對象AutoGenerator mpg = new AutoGenerator();//全局配置GlobalConfig gc = new GlobalConfig();String property = System.getProperty("user.dir");gc.setOutputDir(property+"/src/main/java");gc.setAuthor("奇樂云");gc.setOpen(false);gc.setFileOverride(false);//是否覆蓋gc.setServiceImplName("%sService");//去除Service的I前綴gc.setIdType(IdType.ID_WORKER);gc.setDateType(DateType.ONLY_DATE);gc.setSwagger2(true);mpg.setGlobalConfig(gc);//設置數據源DataSourceConfig dsc= new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);//包的配置PackageConfig pc = new PackageConfig();//pc.setModuleName("blog");//模塊pc.setParent("cn.qileyun.mybatisplus");//包根路徑pc.setEntity("entity");pc.setMapper("mapper");pc.setService("service");pc.setController("controller");mpg.setPackageInfo(pc);//策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("user");//設置要映射的表 可以傳入多個表strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setEntityLombokModel(true);//自動lombokstrategy.setRestControllerStyle(true);strategy.setLogicDeleteFieldName("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);//樂觀鎖strategy.setVersionFieldName("version");strategy.setRestControllerStyle(true);strategy.setControllerMappingHyphenStyle(true);//mpg.setStrategy(strategy);mpg.execute();//執行策略

    看到一個寫的不錯的代碼生成器

    package com.yixin;import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; 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.platform.commons.util.StringUtils;import java.util.ArrayList; import java.util.Scanner;public class CodeGenerator {public static String scanner(String tip) {Scanner scanner = new Scanner(System.in);StringBuilder help = new StringBuilder();help.append("請輸入" + tip + ":");System.out.println(help.toString());if (scanner.hasNext()) {String ipt = scanner.next();if (StringUtils.isNotBlank(ipt)) {return ipt;}}throw new MybatisPlusException("請輸入正確的" + tip + "!");}public static void main(String[] args) {// 代碼生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");//設置代碼生成路徑gc.setFileOverride(true);//是否覆蓋以前文件gc.setOpen(false);//是否打開生成目錄gc.setAuthor("yixin");//設置項目作者名稱gc.setIdType(IdType.AUTO);//設置主鍵策略gc.setBaseResultMap(true);//生成基本ResultMapgc.setBaseColumnList(true);//生成基本ColumnListgc.setServiceName("%sService");//去掉服務默認前綴gc.setDateType(DateType.ONLY_DATE);//設置時間類型mpg.setGlobalConfig(gc);// 數據源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("123456");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setParent("com.yixin");pc.setMapper("mapper");pc.setXml("mapper.xml");pc.setEntity("pojo");pc.setService("service");pc.setServiceImpl("service.impl");pc.setController("controller");mpg.setPackageInfo(pc);// 策略配置StrategyConfig sc = new StrategyConfig();sc.setNaming(NamingStrategy.underline_to_camel);sc.setColumnNaming(NamingStrategy.underline_to_camel);sc.setEntityLombokModel(true);//自動lomboksc.setRestControllerStyle(true);sc.setControllerMappingHyphenStyle(true);sc.setLogicDeleteFieldName("deleted");//設置邏輯刪除//設置自動填充配置TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);ArrayList<TableFill> tableFills=new ArrayList<>();tableFills.add(gmt_create);tableFills.add(gmt_modified);sc.setTableFillList(tableFills);//樂觀鎖sc.setVersionFieldName("version");sc.setRestControllerStyle(true);//駝峰命名// sc.setTablePrefix("tbl_"); 設置表名前綴sc.setInclude(scanner("表名,多個英文逗號分割").split(","));mpg.setStrategy(sc);// 生成代碼mpg.execute();}}
  • 測試看看

    其他參數可以參考官網進行配置,新版本做了很多更新。
  • 總結

    這里是看了狂神說的mybatis plus的入門教程,但是看了官網最新的mybatis plus貌似改了蠻多東西的,有機會多看看官網教程。

    總結

    以上是生活随笔為你收集整理的Mybatis 特别篇 Mybatis-plus入门教程的全部內容,希望文章能夠幫你解決所遇到的問題。

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