本文筆記都是觀看狂神老師視頻手敲的,視頻地址:https://www.bilibili.com/video/BV17E411N7KN
學java后端的都可以去看一下,從基礎到架構很詳細,推薦給大家,狂神說:https://space.bilibili.com/95256449
Mybatis-plus地址:https://mp.baomidou.com/
簡介
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
願景
我們的願景是成為 MyBatis 最好的搭檔,就像 魂斗羅 中的 1P、2P,基友搭配,效率翻倍。
特性
無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
支持數據庫
- mysql 、 mariadb 、 oracle 、 db2 、 h2 、 hsql 、 sqlite 、 postgresql 、 sqlserver
- 達夢數據庫 、 虛谷數據庫 、 人大金倉數據庫
快速指南
我們將通過一個簡單的 Demo 來闡述 MyBatis-Plus 的強大功能,在此之前,我們假設您已經:
擁有 Java 開發環境以及相應 IDE
熟悉 Spring Boot
熟悉 Maven
使用第三方組件:
1、導入對應的依賴
2、研究依賴如何配置
3、代碼如何編寫
4、提高擴展技術的能力
步驟
1、創建數據庫 mybatis_plus
現有一張 User 表,其表結構如下:
其對應的數據庫 Schema 腳本如下:
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) ); -- 真實開發中,version(樂觀鎖),deleted(邏輯刪除)、gmt_create、gem_mo
其對應的數據庫 Data 腳本如下:
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');
2、導入相應的依賴
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mybatis-plus 是自己開發的,非官方的!--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1.tmp</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> <scope>provided</scope> </dependency>
說明:我們使用mybatis-plus可以節省我們大量的代碼,盡量不要同時導入mybatis和mybatis-plus! 版本的差異!
3、連接數據庫
# mysql 5 驅動不同 com.mysql.jsbc.Driver # mysql 8 驅動不同 com.mysql.cj.jsbc.Driver、需要增加時區的配置 spring.datasource.username=root spring.datasource.password=123 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4、編寫代碼
pojo–>dao–>(連接mybatis,配置mapper.xml文件)–>service-controller (傳統方式 )
使用mybatis-plus之后
* pojo
* dao接口(不用寫mapper.xml文件)
* 使用
編寫實體類 User.java(此處使用了 Lombok 簡化代碼)
@Data public class User { private Long id; private String name; private Integer age; private String email; }
編寫Mapper類 UserMapper.java
//在對應的Mapper上繼承基本的類baseMapper public interface UserMapper extends BaseMapper<User> { //所有的CRUD已經編寫完成 //不需要像以前的配置一些xml }
在 Spring Boot 啟動類中添加 @MapperScan 注解,掃描 Mapper 文件夾:
@SpringBootApplication @MapperScan("com.baomidou.mybatisplus.mapper")//掃描mapper文件夾 public class Application { public static void main(String[] args) { SpringApplication.run(QuickStartApplication.class, args); } }
添加測試類,進行功能測試:
@RunWith(SpringRunner.class) @SpringBootTest public class SampleTest { @Autowired private UserMapper userMapper; @Test public void testSelect() { System.out.println(("----- selectAll method test ------")); //參數是一個Wrapper,條件結構器,這里先不用 填null //查詢所有的用戶 List<User> userList = userMapper.selectList(null); Assert.assertEquals(5, userList.size()); userList.forEach(System.out::println); } }
UserMapper 中的 selectList() 方法的參數為 MP 內置的條件封裝器 Wrapper,所以不填寫就是無任何條件
控制台輸出:
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)
完整的代碼示例請移步:Spring Boot 快速啟動示例 [Spring MVC 快速啟動示例]
5、小結
通過以上幾個簡單的步驟,我們就實現了 User 表的 CRUD 功能,甚至連 XML 文件都不用編寫!
從以上步驟中,我們可以看到集成MyBatis-Plus非常的簡單,只需要引入 starter 工程,並配置 mapper 掃描路徑即可。
但 MyBatis-Plus 的強大遠不止這些功能,想要詳細了解 MyBatis-Plus 的強大功能?那就繼續往下看吧!
配置日志
我們所用的sql現在是不可見的,我們希望知道他是怎么執行的,所以我們必須要查看日志!
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
常用注解
@TableName("表名")
當表名與實體類名不一致時,可以在實體類上加入@TableName()聲明
@TableId
聲明屬性為表中的主鍵(若屬性名稱不為默認id)
@TableFieId("字段")
當實體類屬性與表字段不一致時,可以用來聲明
@TableName("表名") public class User{ @TableId private Long userId; @TableFieId("name") private String realName }
CRUD擴展
Insert 插入
// 插入一條記錄 int insert(T entity);
參數說明
類型 | 參數名 | 描述 |
---|---|---|
T | entity | 實體對象 |
距離測試
@Test public void testInsert() { System.out.println(("----- selectAll method test ------")); User user = new User(); user.setName=("shuishui"); user.setAge(3); user.setEmail("12434141@qq.com"); userMapper.insert(user); }
數據庫插入的id為全局默認的id(ID_WORKER)
主鍵生成策略
分布式系統唯一id生成
雪花算法
SnowFlake 算法,是 Twitter 開源的分布式 id 生成算法。其核心思想就是:使用一個 64 bit 的 long 型的數字作為全局唯一 id。在分布式系統中的應用十分廣泛,且ID 引入了時間戳,基本上保持自增的。
這 64 個 bit 中,其中 1 個 bit 是不用的,然后用其中的 41 bit 作為毫秒數,用 10 bit 作為工作機器 id,12 bit 作為序列號。
https://blog.csdn.net/lq18050010830/article/details/89845790
主鍵自增
我們需要配置主鍵自增
1、實體類字段上 @TableId(type =IdType.AUTO)
2、數據庫字段一定要是自增的
其他的碼源詳解
public enum IdType { AUTO(0), //數據可id自增 NONE(1), //未設置主鍵 INPUT(2), //手動輸入 ID_WORKER(3), //默認的全局唯一id UUID(4), //全局唯一id uuid ID_WORKER_STR(5); // ID_WORKEK 字符串表示法 private int key; private IdType(int key) { this.key = key; } public int getKey() { return this.key; } }
更新操作
// 根據 whereEntity 條件,更新記錄 int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); // 根據 ID 修改 int updateById(@Param(Constants.ENTITY) T entity);
#參數說明
類型 | 參數名 | 描述 |
---|---|---|
T | entity | 實體對象 (set 條件值,可為 null) |
Wrapper | updateWrapper | 實體對象封裝操作類(可以為 null,里面的 entity 用於生成 where 語句) |
舉例測試
@Test public void testUpdate() { //sql自動動態配置 User user = new User(); user.setName=("shui"); user.setId(3L); user.setAge("18"); //注意:updateById的參數是一個對象 userMapper.updateById(user); }
自動填充
創建時間、修改時間!這些個操作一遍都是自動化完成,我們不希望手動更新!
阿里巴巴開發手冊:所有的數據庫表:gmt_create\gmt_modified幾乎所有的表都要配置上!而且需要自動化
方式一:數據庫級別
在表中新增字段 create_time 、update_time(默認CURRENT_TIMESIAMP)
方式二:代碼級別
實體類上的屬性需要增加注解==@TableField==
//創建時間 @TableField(fill = FieldFill.INSERT) private Date createTime; //更新時間 @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime;
編寫處理器來處理這個注釋即可!
@Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { //插入時候的填充策略 @Override @Componcent //一定不要忘記吧處理器加到IOC容器中 public void insertFill(MetaObject metaObject) { log.info("start insert fill ...."); //日志 //設置字段的值(String fieldName字段名,Object fieldVal要傳遞的值,MetaObject metaObject) this.setFieldVaLByName("createTime",new Date(),metaObject); this.setFieldVaLByName("createTime",new Date(),metaObject); //this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推薦使用) // this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 該方法有bug請升級到之后的版本如`3.3.1.8-SNAPSHOT`) /* 上面選其一使用,下面的已過時(注意 strictInsertFill 有多個方法,詳細查看源碼) */ //this.setFieldValByName("operator", "Jerry", metaObject); //this.setInsertFieldValByName("operator", "Jerry", metaObject); } //更新時間的填充策略 @Override public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); this.setFieldVaLByName("createTime",new Date(),metaObject); //this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推薦使用) // this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 該方法有bug請升級到之后的版本如`3.3.1.8-SNAPSHOT`) /* 上面選其一使用,下面的已過時(注意 strictUpdateFill 有多個方法,詳細查看源碼) */ //this.setFieldValByName("operator", "Tom", metaObject); //this.setUpdateFieldValByName("operator", "Tom", metaObject); } }
吐槽:這么麻煩,難道用數據庫不香嗎?
樂觀鎖
面試中經常會問到樂觀鎖,悲觀鎖
樂觀鎖:顧名思義十分樂觀,它總是被認為不會出現問題,無論干什么都不去上鎖!如果出現了問題,再次更新測試
悲觀鎖:顧名思義十分悲觀,它總是出現問題,無論干什么都會上鎖!再去操作!
樂觀鎖實現方式
- 取出記錄是,獲取當前version
- 更新事,帶上這個version
- 執行更新事,set version=newVersion where version =oldVersion
- 如果version不對,就更新失敗
樂觀鎖: 1、先查詢,獲得版本號 version=1 --A update user set name ="shuishui" ,version =version+1 where id =2 and version=1 --B 如果線程搶先完成,這個時候version=2,會導致A修改失敗 update user set name ="shuishui" ,version =version+1 where id =2 and version=1
測試樂觀鎖
1、表中創建樂觀鎖字段version 默認值為1
2、同步實體類
@Version //樂觀鎖Version注解 private Integer version;
3、注冊組件 (config包下)
springboot:
@EnableTransactionManagement @MapperScan("com.baomidou.cloud.service.*.mapper*") @Configuration//配置類 public class MyBatisPlusConfig{ //注冊樂觀鎖插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } }
spring xml:
<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>
特別說明:
支持的數據類型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數類型下 newVersion = oldVersion + 1
newVersion 會回寫到 entity 中
僅支持 updateById(id) 與 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能復用!!!
測試一下:
查詢操作
// 根據 ID 查詢 T selectById(Serializable id); // 根據 entity 條件,查詢一條記錄 T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 查詢(根據ID 批量查詢) List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); // 根據 entity 條件,查詢全部記錄 List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 查詢(根據 columnMap 條件) List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); // 根據 Wrapper 條件,查詢全部記錄 List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根據 Wrapper 條件,查詢全部記錄。注意: 只返回第一個字段的值 List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根據 entity 條件,查詢全部記錄(並翻頁) IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根據 Wrapper 條件,查詢全部記錄(並翻頁) IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); // 根據 Wrapper 條件,查詢總記錄數 Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
參數說明
實例測試
@Test public void testSelectById(){ User user =userMapper.selectById(1); System.out.println(user) } //測試批量查詢 @Test public void testSelectByBatchId(){ List<User> user =userMapper.selectBatchIds(Arrays.asList(1,2,3)); users.forEach(System.out::println) } //條件查詢 public void testSelectByBatchIds(){ HashMap<String,Object> map=new HashMap<>(); //自定義查詢 map.put("name","shuishui"); map.put("age",3); List<User> user = userMapper.selectByMap(map); users.forEach(System.out::println); }
查詢指定字段
// QueryWrapper<CasesFeedback> queryWrapper = new QueryWrapper<>(); // queryWrapper.select(CasesFeedback.class,info -> !info.getColumn().equals("create_time")&& // !info.getColumn().equals("update_time") && // !info.getColumn().equals("deleted")&& // !info.getColumn().equals("id"));
自定義sql
方式一:
在Mapper文件中定義一個方法
@Select("select * from user ${ew.customSqlSegment}")
List<User> selectAll(@Param(Constants.WRAPPER)Wrapper<User> wrapper);
方式二:將sql寫入xml中
在application中加入掃描mapper文件路徑
mybatis-plus:
mapper-locations: com/mp/mapper/*
在*Mapper.xml中寫sql
<mapper namespace="com.mp.dao.UserMapper"> <select id="selectAll" resultType="com.mp.entity.User"> select * from user ${ew.customSqlSegment} </select> </mapper>
測試
分頁查詢
分頁在網站使用的十分多
1、原始的limit進行分頁
2、pageHelper 第三方插件
3、Mybatis-Plus中也內置了分頁插件!
如何使用
1、配置攔截器組件即可
//Spring boot方式 @EnableTransactionManagement @Configuration @MapperScan("com.baomidou.cloud.service.*.mapper*") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 設置請求的頁面大於最大頁后操作, true調回到首頁,false 繼續請求 默認false // paginationInterceptor.setOverflow(false); // 設置最大單頁限制數量,默認 500 條,-1 不受限制 // paginationInterceptor.setLimit(500); // 開啟 count 的 join 優化,只針對部分 left join paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); return paginationInterceptor; } }
2、寫測試
//測試分頁查詢 @Test pulic void testPage(){ // 參數一:當前頁 // 參數二:頁面大小 // 使用了分頁插件之后,所有的分頁操作也變得簡單了 Page<User> page =new Page<>(2,5); userMapper.selectPage(page,null); page.getRecords().forEach(System.out::println); //獲取總數 page.getTotal(); }
刪除
// 根據 entity 條件,刪除記錄 int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper); // 刪除(根據ID 批量刪除) int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); // 根據 ID 刪除 int deleteById(Serializable id); // 根據 columnMap 條件,刪除記錄 int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
#參數說明
測試刪除:
@Test public void testDeleteById(){ userMapper.deleteById(1); } //批量刪除 @Test public void testDeleteBatchId(){ userMapper.deleteBatchIds(Arrays.asList(1,2)); } //條件刪除 @Test public void testDeleteMap(){ HashMap<String,Object> map = new HashMap<>(); map.put("name","shuishui"); userMapper.deleteByMap(Map); }
在工作中會遇到邏輯刪除
邏輯刪除
物理刪除 :從數據庫中直接移出
邏輯刪除:在數據庫中沒有被移出,而是通過一個變量來讓他失效!deleted=0 ==>deleted =1(失效)
SpringBoot 配置方式:
- application.yml 加入配置(如果你的默認值和mp默認的一樣,該配置可無):
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag #全局邏輯刪除字段值 3.3.0開始支持,詳情看下面。
logic-delete-value: 1 # 邏輯已刪除值(默認為 1)
logic-not-delete-value: 0 # 邏輯未刪除值(默認為 0)
- 注冊 Bean(3.1.1開始不再需要這一步):
import com.baomidou.mybatisplus.core.injector.ISqlInjector; import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyBatisPlusConfiguration { @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); } }
- 實體類字段上加上@TableLogic注解
@TableLogic private Integer deleted;
- 效果: 使用mp自帶方法刪除和查找都會附帶邏輯刪除功能 (自己寫的xml不會)
example 刪除時 update user set deleted=1 where id =1 and deleted=0 查找時 select * from user where deleted=0
- 全局邏輯刪除: 3.3.0開始支持
如果公司代碼比較規范,比如統一了全局都是flag為邏輯刪除字段。
使用此配置則不需要在實體類上添加 @TableLogic。
但如果實體類上有 @TableLogic 則以實體上的為准,忽略全局。 即先查找注解再查找全局,都沒有則此表沒有邏輯刪除。
mybatis-plus: global-config: db-config: logic-delete-field: flag #全局邏輯刪除字段值
附件說明
- 邏輯刪除是為了方便數據恢復和保護數據本身價值等等的一種方案,但實際就是刪除。
- 如果你需要再查出來就不應使用邏輯刪除,而是以一個狀態去表示。如: 員工離職,賬號被鎖定等都應該是一個狀態字段,此種場景不應使用邏輯刪除。
- 若確需查找刪除數據,如老板需要查看歷史所有數據的統計匯總信息,請單獨手寫sql。
以上的CRUD操作都必須要掌握
通用service
配置:
1、創建一個service接口:
public interface UserService extends IService<User>{ }
2、創建實現類
public class UserServiceImpl extend ServiceImol<UserMapper,User> implements UserService{ }
3、測試方法
@RunWith(SpringRunner.class) @SpringBootTest public class ServiceTest{ @Autowired private UserService userService; //取一個值 @Test public void getOne(){ User one = userService.getOne(Wrapper.<User>lambdaQuery().gt(User::getAge,25),false); } //批量插入 @Test public void batch(){ User user1= new User(); user1.steName("shui"); user1.setAge("28"); User user2= new User(); user1.steName("shui2"); user1.setAge("29"); List<User> userList =Arrays.asList(user1,user2); userService.saveBatch(userList); } @Test public void chain(){ //查詢 userService.lambdaQuery().ge(User::getAge,25).like(User::getName,"雨").list(); } }
性能更新插件
我們在平時的開發中,會遇到一些慢sql。測試!druid…
作用:性能分析攔截器,用於輸出每條SQL語句及執行時間
MP也提供性能分析插件,如果超過這和時間就會停止運行
1、導入插件
//Spring boot方式 @EnableTransactionManagement @Configuration @MapperScan("com.baomidou.cloud.service.*.mapper*") public class MybatisPlusConfig { /** * SQL執行效率插件 */ @Bean @Profile({"dev","test"})// 設置 dev test 環境開啟 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(100);// ms 設置sql執行的最大時間,如果超過就停止 performanceInterceptor.setFormat(true); return new PerformanceInterceptor(); } }
記得在SpringBoot配置環境為dev或者test環境!
2、測試使用
@Test void contextLoads(){ //參數是一個Wrapper,條件結構器,這里先不用,填null //查詢全部用戶 List<User> users =userMapper.selectList(null); user.forEach(System.out::println); }
注意!參數說明:
- 參數:maxTime SQL 執行最大時長,超過自動停止運行,有助於發現問題。
- 參數:format SQL SQL是否格式化,默認false。
- 該插件只用於開發環境,不建議生產環境使用。
條件構造器(Wrapper)
十分重要:Wrapper
我們寫一些復雜的sql可以用它來完成
現做幾個實例看看:
@Test void contextLoads(){ // 查詢name不為null的用戶,並且郵箱不為null的永不,年齡大於等於20的用戶 QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.isNotNull("name"); wrapper.isNotNull("email"); wrapper.ge("age",12); userMapper.selectList(wrapper).forEach(System.out::println); } @Test void test2(){ // 查詢name為shuishui的用戶 QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.eq("name","shuishui"); User user=userMapper.selectList(wrapper) System.out.println(user); } @Test void test3(){ // 查詢年齡在20~30歲之間的用戶 QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.between("age",20,30); Integer count =userMapper.selectCount(wrapper);//查詢結果數 System.out.println(count); } //模糊查詢 @Test void test4(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.notLike("name",“s”);//相當於NOT LIKE '%s%' wrapper.likeRight("email",“s”);//相當於LIKE 's%' List<Map<String,Object>>maps =userMapper.selectMaps(wrapper);//查詢結果數 maps.forEach(System.out::println); } @Test void test5(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); //子查詢 wrapper.insql("id","select id from user where id<3"); List<Object> objects =userMapper.selectobjs(wrapper); objects.forEach(System.out::println); } @Test void test6(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); //通過id進行排序 wrapper.orderByAsc("id"); List<User> users =userMapper.selectList(wrapper); objects.forEach(System.out::println); } //姓王年齡大於等於25,按年齡降序,年齡相同按id升序排列 void test7(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.likeRoght("name","王").or().ge("age",25).ordeiByDesc("age").orderByAsc("id"); List<User> users =userMapper.selectList(wrapper); objects.forEach(System.out::println); } //創建日期為2019年2月14日並且直屬上級為姓王 void test8(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.apply("date_fromat(create_time,'%Y-%m-%d')='2019-02-14'").inSql("manager_id","select id from user where name like '王%'"); List<User> users =userMapper.selectList(wrapper); objects.forEach(System.out::println); } //姓王並且(年齡小於40或者郵箱不為空) void test9(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); //lt小於,gt大於 wrapper.likeRoght("name","王").and(wq->wa.lt("age",40).or().isNotNull("email")) List<User> users =userMapper.selectList(wrapper); objects.forEach(System.out::println); } //不列出所有字段 @Test void test10(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); wrapper.select("id","name").like("name","雨").lt("age",40); //不顯示時間和id //wrapper.select(User.class,info->!info.getColumn().equals("create_time")&&!info.getColumn().equals("manager_id")).like("name","雨").lt("age",40); List<User> users =userMapper.selectList(wrapper); objects.forEach(System.out::println); }
更多的方法都在官方文檔里
condition的用法
alleq的用法
allEq(Map<R, V> params) allEq(Map<R, V> params, boolean null2IsNull) allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
全部eq(或個別isNull)
個別參數說明:
params : key為數據庫字段名,value為字段值
null2IsNull : 為true則在map的value為null時調用 isNull 方法,為false時則忽略value為null的
- 例1: allEq({id:1,name:"老王",age:null})—>id = 1 and name = '老王' and age is null
- 例2: allEq({id:1,name:"老王",age:null}, false)—>id = 1 and name = '老王'
allEq(BiPredicate<R, V> filter, Map<R, V> params) allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull) allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
個別參數說明:
filter : 過濾函數,是否允許字段傳入比對條件中
params 與 null2IsNull : 同上
- 例1: allEq((k,v) -> k.indexOf("a") >= 0, {id:1,name:"老王",age:null})—>name = '老王' and age is null
- 例2: allEq((k,v) -> k.indexOf("a") >= 0, {id:1,name:"老王",age:null}, false)—>name = '老王'
實例測試
@Test void selecrAlleq(){ QueryWrapper<User> wrapper =new QueryWrapper<>(); Map<String,Object> params=new HashMap<String,Object>(); params.put("name","水"); params.put("age",25); wrapper.allEq(params); List<User> users =userMapper.selectList(wrapper); users.forEach(System.out::println); }
Lambda 條件構造器
作用:防誤寫!
@Test public void selectLambda(){ // LambdaQueryWrapper<User> lambda =new QueryWrapper<User>().lambda(); // LambdaQueryWrapper<User> lambda =new LambdaQueryWrapper<User>(); LambdaQueryWrapper<User> lambda =new Wrapper.<User>lambdaQuery(); lambda.like(User::getName,"雨").lt(User::getAge,40); //寫錯會直接爆紅 List<user> userList =userMapper.selectList(lambdaQuery); userList.forEach(System.out::println); }
AR模式
通過實體類對象直接實現CRUD
實體類操作:
@Data @EqualsAndHashCode(callSuper = false) public class User extends Model<User> { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "用戶id") private String userId; }
dao層Mapper接口操作:
public interface UserMapper extends BaseMapper<RentDetail> { }
實例測試:
// 測試插入 @Test public void insert(){ User user =new User(); user.setName("水"); user.setAge(29); ... user.insert(); //不用再調用mapper接口,直接實現 } // 測試查詢 @Test public void select(){ User user =new User(); user.selectById(1); } @Test public void select2(){ User user =new User(); user.setId(1); user.selectById(); } //測試更新 @Test public void update(){ User user =new User(); user.setId(1); user.setName("火") user.updateById(); } //測試刪除 @Test public void delete(){ User user =new User(); user.setId(1); user.deleteById(); }
代碼自動生成器
dao、pojo、conrtroller、service自動生成
package com.kuang; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; 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 java.util.ArrayList; // 代碼自動生成器 public class KuangCode { public static void main(String[] args) { // 需要構建一個 代碼自動生成器 對象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath+"/src/main/java"); gc.setAuthor("狂神說"); gc.setOpen(false); gc.setFileOverride(false);// 是否覆蓋 gc.setServiceName("%sService");// 去Service的I前綴 gc.setIdType(IdType.ID_WORKER); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true); mpg.setGlobalConfig(gc); //2、設置數據源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("blog"); pc.setParent("com.kuang"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("blog_tags","course","links","sys_settings","user_record"," user_say"); // 設置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true);// 自動lombok; 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); // localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //執行 } }