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語句中只需要調用一個方法即可完成增刪改查

正如官方所介紹為簡化開發而生
一、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.快速入門(官網案例)
參考地址
- 傳統mybatis寫法依然支持不做介紹,可參考mybatis原生案例
- 使用mybatis-plus (pojo->mapper接口->使用)我們可以看到都不需要配置xml文件
創建User實體類
創建Mapper接口
//在對應的Mapper上面是實現基本的接口BaseMapper @Repository public interface UserMapper extends BaseMapper<User> { //所有的crud的擦歐總已經編寫完畢了 }簡單看看baseMapper里面已經定義好啦非常多的接口
入口文件增加注解掃描Mapper
@MapperScan("cn.qileyun.mybatisplus.mapper")
測試一下看看
2. 配置日志輸出
#配置日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl3. 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 雪花算法
5. 自動填充
6. 樂觀鎖
-
樂觀鎖:顧名思義十分樂觀,它總是認為不會出現問題,無論干什么不去上鎖!如果出現了問題,在次更新值測試
-
悲觀鎖:顧名思義十分悲觀,無論干什么都會上鎖!再去操作!
-
取出記錄時,獲取當前version
-
更新時,帶上version
-
執行更新時,set version = newVersion where = version = oldVersion
-
如果version不對,就更新失敗
使用樂觀鎖插件
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其實內置了分頁插件
使用教程
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
實體類增加字段
其實執行的不在是delete操作了而是更新了字段吧deleted = 1
查詢看看可以看出已經自動加上了deleted = 0的條件,判斷是否被刪除過
9. 性能分析插件(好像新版被移除了)
MP提供了性能分析插件,如果超過這個時間就停止運行!
如果這個時間超過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. 代碼生成器
看到一個寫的不錯的代碼生成器
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入门教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高通camx debug log 控制
- 下一篇: 计算机考研专业课除了408,计算机改考4