Mybatis-Plus 新手入门,一篇足以
目錄
一、MyBatis-Plus簡介
1.簡介
2.特性
3.支持數據庫
4.框架結構
5.官方地址
二、入門案例
1.開發環境
2.建庫建表
3.創建工程
4.配置編碼
1.BaseMapper
5.測試查詢
三、增刪改查
1.BaseMapper
2.調用Mapper層實現CRUD
2.1 插入
2.2 刪除
2.3 修改
2.4 查詢
3.通用Service
4.調用Service層操作數據
四、常用注解
1.@TableName
1.1 引出問題
1.2 解決問題
2.@TableId
2.1 引出問題
2.2 解決問題
2.3 @TableId的value屬性
2.4 @TableId的type屬性
3.@TbaleField
3.1 情況一
3.2 情況二
4.@TableLogic
4.1 邏輯刪除
4.2 實現邏輯刪除
五、條件構造器
1.Wrapper介紹
2.QueryWrapper
3.UpdateWrapper
4.condition參數
5.LambdaQueryWrapper
6.LambdaUpdateWrapper
六、常用插件
1.分頁插件
2.自定義分頁
3.樂觀鎖
3.1 場景
3.2 樂觀鎖與悲觀鎖
3.3 模擬修改沖突
3.4 樂觀鎖解決問題
七、通用枚舉
八、代碼生成器
1、引入依賴
2、快速生成
九、多數據源
1.創建數據庫及表
2.新建工程引入依賴
3.編寫配置文件
4.創建實體類
5.創建Mapper及Service
6.編寫測試方法
十、MyBatisX插件
1.安裝MyBatisX插件
2.快速生成代碼
3.快速生成CRUD
一、MyBatis-Plus簡介
1.簡介
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
我們的愿景是成為 MyBatis 最好的搭檔,就像 魂斗羅 中的 1P、2P,基友搭配,效率翻倍。
2.特性
-
無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
-
損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
3.支持數據庫
任何能使用 MyBatis 進行 CRUD, 并且支持標準 SQL 的數據庫,具體支持情況如下,如果不在下列表查看分頁部分教程 PR 您的支持。
-
MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
-
達夢數據庫,虛谷數據庫,人大金倉數據庫,南大通用(華庫)數據庫,南大通用數據庫,神通數據庫,瀚高數據庫
4.框架結構
先去掃描實體類(scan entity),通過反射抽取(reflection extraction)抽取實體類中的屬性,抽取出來再去分析要操作的表是誰,要操作的實體類中的屬性是誰字段是誰,再去生成sql語句,把他注入到mybati容器中,我們要操作的表要交給實體類和實體類的屬性決定
5.官方地址
官方網站:MyBatis-Plus
官方文檔:簡介 | MyBatis-Plus
二、入門案例
1.開發環境
-
IDE:IDEA 2019.3.5
-
JDK:JDK8+
-
構建工具:Maven 3.5.4
-
MySQL:MySQL 8.0.24
-
Navicat:Navicat Premium 15
-
Spring Boot:2.6.7
-
MyBatis-Plus:3.5.1
2.建庫建表
-
打開Navicat運行以下SQL腳本進行建庫建表
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; use `mybatis_plus`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL COMMENT '主鍵ID', `name` varchar(30) DEFAULT NULL COMMENT '姓名', `age` int(11) DEFAULT NULL COMMENT '年齡', `email` varchar(50) DEFAULT NULL COMMENT '郵箱', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -
插入幾條測試數據
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');
3.創建工程
-
使用Spring Initializer快速初始化一個 Spring Boot 工程
-
引入MyBatis-Plus的依賴
<!--mybatis-plus啟動器--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version> </dependency> ?<!-- 數據庫驅動 --> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency> -
最全jar依賴包 如果上面截圖操作最后一步不勾選的情況下可以直接把以下依賴全部復制到prom文件中
<dependencies> ?<!--web場景開發啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency> ? ?<!--lombok:簡化實體類開發--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency> ?<!--開啟測試啟動器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> ?<!-- 數據庫驅動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency> ?<!-- mybatis-plus啟動器--><!-- mybatis-plus 是自己開發,并非官方的! --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version></dependency> ?<!--多數據源依賴--><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency> ? </dependencies> -
安裝Lombok插件
4.配置編碼
-
配置application.yaml文件
spring:#配置數據庫datasource:# 配置連接數據庫信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8username: rootpassword: 123456 ? mybatis-plus:# 配置MyBatis日志configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ?#全局配置global-config:db-config:#配置統一的主鍵策略為自增,如果不設置默認為雪花算法id-type: auto# 設置實體類所對應的表的統一前綴,為實體類所對應的表名設置默認的前綴table-prefix: t_ ?#配置mapper映射文件路徑,名字要和mapper接口名字一致 這是默認路徑不寫也行mapper-locations: classpath*:/mapper/**/*.xml ?#配置類型別名所對應的包type-aliases-package: com.yka.boot02mybatis_plus.pojo ?# 掃描通用枚舉的包type-enums-package: com.yka.boot02mybatis_plus.enums -
創建一個config包創建配置類,添加@MapperScan` 注解,掃描 Mapper 文件夾 添加@Configuration注解**
@Configuration //告訴SpringBoot這是一個配置類 == spring配置文件 @MapperScan("com.yka.boot02mybatis_plus.mapper")//掃描接口包 在當前配置類(spring.xml)中填寫注解最合適 //配置mapper接口的掃描配置 //由mybatis-spring提供,可以將指定包下所有的mapper接口創建代理實現類 //并將這些動態代理作為IOC容器的bean管理,接口就可以自動裝配了,直接可以調用接口中的方法 public class MyConfig { } -
編寫實體類 User.java(此處使用了 Lombok 簡化代碼)
@Data//自動提供get set方法、tosString方法,equals方法 @AllArgsConstructor//有參構造器 @NoArgsConstructor//無參構造器 @TableName("user")//綁定表 yaml文件中設置了全局配置這里可以不用注解了 yaml文件配置文件中:db-config:table-prefix: t_ public class User {private Long id;private String name;private Integer age;private String email; } -
編寫 Mapper 包下的 UserMapper接口
-
1.BaseMapper<T>
說明:
-
通用 CRUD 封裝BaseMapper 接口,為 Mybatis-Plus 啟動時自動解析實體表關系映射轉換為 Mybatis 內部對象注入容器
-
泛型 T 為任意實體對象
-
參數 Serializable 為任意類型主鍵 Mybatis-Plus 不推薦使用復合主鍵約定每一張表都有自己的唯一 id 主鍵
-
對象 Wrapper 為條件構造器
MyBatis-Plus中的基本CRUD在內置的BaseMapper中都已得到了實現,因此我們繼承該接口以后可以直接使用。
本次演示的CRUD操作不包含參數帶有條件構造器的方法,關于條件構造器將單獨在一個章節進行演示。BaseMapper中提供的CRUD方法:
-
- // 在對應的Mapper上面繼承基本的類 BaseMapper,就能直接用BaseMapper接口里面的sql語句了 //MyBatis-Plus中的基本CRUD在內置的BaseMapper中都已得到了實現,因此我們繼承該接口以后可以直接使用。 @Repository // 代表持久層 public interface UserMapper extends BaseMapper<User> { // 所有的CRUD操作都已經編寫完成了 // 你不需要像以前的配置一大堆文件了! ?@Select("select * from user where id = #{id}")public User selById(Integer id); ? }
5.測試查詢
-
編寫一個測試類MyBatisPlusTest.java
@SpringBootTest public class MyBatisPlusTest {@Resourceprivate UserMapper userMapper; ?/*** 測試查詢所有數據*/@Testvoid testSelectList(){//通過條件構造器查詢一個list集合,若沒有條件,則可以設置null為參數List<User> users = userMapper.selectList(null);users.forEach(System.out::println);} } -
控制臺打印查詢結果
三、增刪改查
1.BaseMapper<T>
說明:
-
通用 CRUD 封裝BaseMapper 接口,為 Mybatis-Plus 啟動時自動解析實體表關系映射轉換為 Mybatis 內部對象注入容器
-
泛型 T 為任意實體對象
-
參數 Serializable 為任意類型主鍵 Mybatis-Plus 不推薦使用復合主鍵約定每一張表都有自己的唯一 id 主鍵
-
對象 Wrapper 為條件構造器
MyBatis-Plus中的基本CRUD在內置的BaseMapper中都已得到了實現,因此我們繼承該接口以后可以直接使用。
本次演示的CRUD操作不包含參數帶有條件構造器的方法,關于條件構造器將單獨在一個章節進行演示。
BaseMapper中提供的CRUD方法:
-
增加:Insert
// 插入一條記錄 int insert(T entity); -
刪除:Delete
// 根據 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); -
修改:Update
// 根據 whereWrapper 條件,更新記錄 int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper); // 根據 ID 修改 int updateById(@Param(Constants.ENTITY) T entity); -
查詢:Selete
// 根據 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);
2.調用Mapper層實現CRUD
2.1 插入
最終執行的結果,所獲取的id為1527206783590903810
這是因為MyBatis-Plus在實現插入數據時,會默認基于雪花算法的策略生成id
/*** 測試插入一條數據 INSERT INTO user ( name, age, email ) VALUES ( ?, ?, ? )* MyBatis-Plus在實現插入數據時,會默認基于雪花算法的策略生成id,后面常用注解可以修改*/ @Test public void testInsert(){User user = new User();user.setName("Vz");user.setAge(21);user.setEmail("vz@oz6.cn");int result = userMapper.insert(user);System.out.println(result > 0 ? "添加成功!" : "添加失敗!");System.out.println("受影響的行數為:" + result);//1527206783590903810(當前 id 為雪花算法自動生成的id)System.out.println("id自動獲取" + user.getId()); }2.2 刪除
a、根據ID刪除數據
調用方法:int deleteById(Serializable id);
/*** 測試根據id刪除一條數據 DELETE FROM user WHERE id=?*/ @Test public void testDeleteById(){int result = userMapper.deleteById(1527206783590903810L);System.out.println(result > 0 ? "刪除成功!" : "刪除失敗!");System.out.println("受影響的行數為:" + result); }b、根據ID批量刪除數據
調用方法:int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/*** 測試通過id批量刪除數據 DELETE FROM user WHERE id IN ( ? , ? )*/ @Test public void testDeleteBatchIds(){List<Long> ids = Arrays.asList(6L,7L,8L);int result = userMapper.deleteBatchIds(ids);System.out.println(result > 0 ? "刪除成功!" : "刪除失敗!");System.out.println("受影響的行數為:" + result); } //刪除所有數據 DELETE FROM user userMapper.delete(null);c、根據Map條件刪除數據
調用方法:int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/*** 測試根據Map集合中所設置的條件刪除數據 ?*/ @Test public void testDeleteByMap(){//當前演示為根據name和age刪除數據//執行SQL為:DELETE FROM user WHERE name = ? AND age = ?Map<String,Object> map = new HashMap<>();map.put("name","Vz");map.put("age",21);int result = userMapper.deleteByMap(map);System.out.println(result > 0 ? "刪除成功!" : "刪除失敗!");System.out.println("受影響的行數為:" + result); }2.3 修改
調用方法:int updateById(@Param(Constants.ENTITY) T entity);
/*** 測試根據id修改用戶信息*/ @Test public void testUpdateById(){//執行SQL為: UPDATE user SET name=?, age=?, email=? WHERE id=?User user = new User();user.setId(6L);user.setName("VzUpdate");user.setAge(18);user.setEmail("Vz@sina.com");int result = userMapper.updateById(user);System.out.println(result > 0 ? "修改成功!" : "修改失敗!");System.out.println("受影響的行數為:" + result); }2.4 查詢
a、根據ID查詢用戶信息
調用方法:T selectById(Serializable id);
/*** 測試根據id查詢用戶數據 SELECT id,name,age,email FROM user WHERE id=?*/ @Test public void testSelectById(){User user = userMapper.selectById(1L);System.out.println(user); }b、根據多個ID查詢多個用戶信息
調用方法:List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/*** 根據多個id查詢用戶數據*/ @Test public void testSelectBatchIds(){//執行SQL為:SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )List<Long> ids = Arrays.asList(1L,2L,3L);List<User> users = userMapper.selectBatchIds(ids);users.forEach(System.out::println); }c、根據Map條件查詢用戶信息
調用方法:List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/*** 根據Map所設置的條件查詢用戶*/ @Test public void testSelectByMap(){//執行SQL為:SELECT id,name,age,email FROM user WHERE age = ?Map<String,Object> map = new HashMap<>();map.put("age",18);List<User> users = userMapper.selectByMap(map);users.forEach(System.out::println); }d、查詢所有用戶信息
調用方法:List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/*** 測試查詢所有數據 SELECT id,name,age,email FROM user*/ @Test void testSelectList(){List<User> users = userMapper.selectList(null);users.forEach(System.out::println); }3.通用Service
說明:
-
通用 Service CRUD 封裝IService接口,進一步封裝 CRUD 采用 get 查詢單行 remove 刪除 list 查詢集合 page 分頁 前綴命名方式區分 Mapper 層避免混淆,
-
泛型 T 為任意實體對象
-
建議如果存在自定義通用 Service 方法的可能,請創建自己的 IBaseService 繼承 Mybatis-Plus 提供的基類
-
對象 Wrapper 為 條件構造器
MyBatis-Plus中有一個接口 IService和其實現類 ServiceImpl,封裝了常見的業務層邏輯,詳情查看源碼IService和ServiceImpl
因此我們在使用的時候僅需在自己定義的Service接口中繼承IService接口,在自己的實現類中實現自己的Service并繼承ServiceImpl即可
IService中的CRUD方法
-
增加:Save、SaveOrUpdate
// 插入一條記錄(選擇字段,策略插入) boolean save(T entity); // 插入(批量) boolean saveBatch(Collection<T> entityList); // 插入(批量) boolean saveBatch(Collection<T> entityList, int batchSize); ? // TableId 注解存在更新記錄,否插入一條記錄 //saveOrUpdate:會去表里查該id,如果表里有該id修改,無id是增加,新增不需要id,更改需要id boolean saveOrUpdate(T entity); // 根據updateWrapper嘗試更新,否繼續執行saveOrUpdate(T)方法 boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper); // 批量修改插入 會去表里查該id,如果表里有該id修改,無id是增加,新增不需要id,更改需要id boolean saveOrUpdateBatch(Collection<T> entityList); // 批量修改插入 有id修改無id是增加 boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize); -
刪除:Remove
// 根據 entity 條件,刪除記錄 boolean remove(Wrapper<T> queryWrapper); // 根據 ID 刪除 boolean removeById(Serializable id); // 根據 columnMap 條件,刪除記錄 boolean removeByMap(Map<String, Object> columnMap); // 刪除(根據ID 批量刪除) boolean removeByIds(Collection<? extends Serializable> idList); -
修改:Update
// 根據 UpdateWrapper 條件,更新記錄 需要設置sqlset boolean update(Wrapper<T> updateWrapper); // 根據 whereWrapper 條件,更新記錄 boolean update(T updateEntity, Wrapper<T> whereWrapper); // 根據 ID 選擇修改 boolean updateById(T entity); // 根據ID 批量更新 有id修改無id是增加 boolean updateBatchById(Collection<T> entityList); // 根據ID 批量更新 有id修改無id是增加 boolean updateBatchById(Collection<T> entityList, int batchSize); -
查詢:Get、List、Count
// 根據 ID 查詢 T getById(Serializable id); // 根據 Wrapper,查詢一條記錄。結果集,如果是多個會拋出異常,隨機取一條加上限制條件 wrapper.last("LIMIT 1") T getOne(Wrapper<T> queryWrapper); // 根據 Wrapper,查詢一條記錄 T getOne(Wrapper<T> queryWrapper, boolean throwEx); // 根據 Wrapper,查詢一條記錄 Map<String, Object> getMap(Wrapper<T> queryWrapper); // 根據 Wrapper,查詢一條記錄 <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); ? ? // 查詢所有 List<T> list(); // 查詢列表 List<T> list(Wrapper<T> queryWrapper); // 查詢(根據ID 批量查詢) Collection<T> listByIds(Collection<? extends Serializable> idList); // 查詢(根據 columnMap 條件) Collection<T> listByMap(Map<String, Object> columnMap); // 查詢所有列表 List<Map<String, Object>> listMaps(); // 查詢列表 List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper); // 查詢全部記錄 List<Object> listObjs(); // 查詢全部記錄 <V> List<V> listObjs(Function<? super Object, V> mapper); // 根據 Wrapper 條件,查詢全部記錄 List<Object> listObjs(Wrapper<T> queryWrapper); // 根據 Wrapper 條件,查詢全部記錄 <V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); ? // 查詢總記錄數 int count(); // 根據 Wrapper 條件,查詢總記錄數 int count(Wrapper<T> queryWrapper); -
分頁:Page
default <E extends IPage<T>> E page(E page, Wrapper<T> queryWrapper) {}
4.調用Service層操作數據
我們在自己的Service接口中通過繼承MyBatis-Plus提供的IService接口,不僅可以獲得其提供的CRUD方法,而且還可以使用自身定義的方法。
-
創建UserService并繼承IService
/*** UserService繼承IService模板提供的基礎功能 */ public interface UserService extends IService<User> {} -
創建UserService的實現類并繼承ServiceImpl
/*** ServiceImpl實現了IService,提供了IService中基礎功能的實現 * 若ServiceImpl無法滿足業務需求,則可以使用自定的UserService定義方法,并在實現類中實現*/ @Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{} -
測試查詢記錄數
調用方法:int count();
@Test public void testGetCount(){//查詢總記錄數//執行的SQL為:SELECT COUNT( * ) FROM userlong count = userService.count();System.out.println("總記錄數:" + count); }
四、常用注解
MyBatis-Plus提供的注解可以幫我們解決一些數據庫與實體之間相互映射的問題。
1.@TableName
經過以上的測試,在使用MyBatis-Plus實現基本的CRUD時,我們并沒有指定要操作的表,只是在Mapper接口繼承BaseMapper時,設置了泛型User,而操作的表為user表,由此得出結論,MyBatis-Plus在確定操作的表時,由BaseMapper的泛型決定,即實體類型決定,且默認操作的表名和實體類型的類名一致。
1.1 引出問題
若實體類類型的類名和要操作的表的表名不一致,會出現什么問題?
-
我們將表user更名為t_user,測試查詢功能
-
程序拋出異常,Table 'mybatis_plus.user' doesn't exist,因為現在的表名為t_user,而默認操作的表名和實體類型的類名一致,即user表
1.2 解決問題
a、使用注解解決問題
在實體類類型上添加@TableName("t_user"),標識實體類對應的表,即可成功執行SQL語句
@Data @TableName("t_user") public class User {private Long id;private String name;private Integer age;private String email; }b、使用全局配置解決問題
在開發的過程中,我們經常遇到以上的問題,即實體類所對應的表都有固定的前綴,例如 t_ 或 tbl_ 此時,可以使用MyBatis-Plus提供的全局配置,為實體類所對應的表名設置默認的前綴,那么就不需要在每個實體類上通過@TableName標識實體類對應的表
mybatis-plus:global-config:db-config:# 設置實體類所對應的表的統一前綴table-prefix: t_2.@TableId
經過以上的測試,MyBatis-Plus在實現CRUD時,會默認將id作為主鍵列,并在插入數據時,默認基于雪花算法的策略生成id
2.1 引出問題
若實體類和表中表示主鍵的不是id,而是其他字段,例如uid,MyBatis-Plus會自動識別uid為主鍵列嗎?
-
我們實體類中的屬性id改為uid,將表中的字段id也改為uid,測試添加功能
-
程序拋出異常,Field 'uid' doesn't have a default value,說明MyBatis-Plus沒有將uid作為主鍵賦值
2.2 解決問題
在實體類中uid屬性上通過@TableId將其標識為主鍵,即可成功執行SQL語句
@Date public class User {//將屬性所對應的字段指定為主鍵@TableIdprivate Long uid;private String name;private Integer age;private String email; }2.3 @TableId的value屬性
若實體類中主鍵對應的屬性為id,而表中表示主鍵的字段為uid,此時若只在屬性id上添加注解@TableId,則拋出異常Unknown column 'id' in 'field list',即MyBatis-Plus仍然會將id作為表的主鍵操作,而表中表示主鍵的是字段uid此時需要通過@TableId注解的value屬性,指定表中的主鍵字段,@TableId("uid")或@TableId(value="uid")
2.4 @TableId的type屬性
type屬性用來定義主鍵策略:默認雪花算法
常用的主鍵策略:
| IdType.ASSIGN_ID(默認) | 基于雪花算法的策略生成數據id,與數據庫id是否設置自增無關 |
| IdType.AUTO | 使用數據庫的自增策略,注意,該類型請確保數據庫設置了id自增, |
配置全局主鍵策略:配置好了就不用在實體類中寫注解了
#MyBatis-Plus相關配置 mybatis-plus:configuration:#配置日志log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:#配置統一的主鍵策略為自增id-type: auto# 設置實體類所對應的表的統一前綴table-prefix: t_3.@TbaleField
經過以上的測試,我們可以發現,MyBatis-Plus在執行SQL語句時,要保證實體類中的屬性名和表中的字段名一致
如果實體類中的屬性名和字段名不一致的情況,會出現什么問題呢?
3.1 情況一
若實體類中的屬性使用的是駝峰命名風格,而表中的字段使用的是下劃線命名風格
例如實體類屬性userName,表中字段user_name
此時MyBatis-Plus會自動將下劃線命名風格轉化為駝峰命名風格
相當于在MyBatis中配置
3.2 情況二
若實體類中的屬性和表中的字段不滿足情況1
例如實體類屬性name,表中字段username
此時需要在實體類屬性上使用@TableField("username")設置屬性所對應的字段名
public class User {@TableId("uid")private Long id;@TableField("username")private String name;private Integer age;private String email; }4.@TableLogic
4.1 邏輯刪除
物理刪除:真實刪除,將對應數據從數據庫中刪除,之后查詢不到此條被刪除的數據
邏輯刪除:假刪除,將對應數據中代表是否被刪除字段的狀態修改為“被刪除狀態”,之后在數據庫中仍舊能看到此條數據記錄
使用場景:可以進行數據恢復
4.2 實現邏輯刪除
-
數據庫中創建邏輯刪除狀態列,設置默認值為0 0未刪除,1已刪除
-
實體類中添加邏輯刪除屬性
-
測試刪除功能,真正執行的是修改
public void testDeleteById(){int result = userMapper.deleteById(1527472864163348482L);System.out.println(result > 0 ? "刪除成功!" : "刪除失敗!");System.out.println("受影響的行數為:" + result); } -
此時執行查詢方法,查詢的結果為自動添加條件is_deleted=0,查詢的是未刪除的數據
五、條件構造器
1.Wrapper介紹
-
Wrapper : 條件構造抽象類,最頂端父類
-
AbstractWrapper: 用于查詢條件封裝,生成 sql 的 where 條件?
-
QueryWrapper: 查詢條件封裝
-
UpdateWrapper: Update 條件封裝
-
AbstractLambdaWrapper: 使用Lambda 語法
-
LambdaQueryWrapper:用于Lambda語法使用的查詢Wrapper
-
LambdaUpdateWrapper: Lambda 更新封裝Wrapper
-
-
2.QueryWrapper
-
組裝查詢條件
@Testpublic void test01(){//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)//查詢用戶名包含a,年齡在20到30之間,郵箱信息不為null的用戶信息QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("name","a").between("age",20,30).isNotNull("email");List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);} -
組裝排序條件
@Testpublic void test02(){//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,id ASC//查詢用戶信息,按照年齡的降序排序,若年齡相同,則按照id升序排序QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.orderByDesc("age").orderByAsc("id");List<User> users = userMapper.selectList(queryWrapper);users.forEach(System.out::println);} -
組裝刪除條件
執行SQL:UPDATE t_user SET is_deleted=1 WHERE is_deleted=0 AND (email IS NULL)
public void test03(){//刪除郵箱地址為null的用戶信息QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.isNull("email");int result = userMapper.delete(queryWrapper);System.out.println(result > 0 ? "刪除成功!" : "刪除失敗!");System.out.println("受影響的行數為:" + result); } -
修改功能
@Testpublic void test04(){//將(年齡大于20并且用戶名中包含有a)或郵箱為null的用戶信息修改//UPDATE t_user SET name=?, email=? WHERE is_deleted=0 AND (age > ? AND name LIKE ? OR email IS NULL)QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age",20).like("name","a").or().isNull("email");User user = new User();user.setName("小明");user.setEmail("test@oz6.com"); ?int result = userMapper.update(user,queryWrapper);System.out.println(result > 0 ? "修改成功!" : "修改失敗!");System.out.println("受影響的行數為:" + result);}條件的優先級
@Testpublic void test05(){//將用戶名中包含有a并且(年齡大于20或郵箱為null)的用戶信息修改//UPDATE t_user SET name=?, email=? WHERE is_deleted=0 AND (name LIKE ? AND (age > ? OR email IS NULL))//lambda中優先執行,i就是條件構造器queryWrapper .and()和.or()都有lambda表達式QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like("name","a").and(i-> i.gt("age",20).or().isNull("email")); ?User user = new User();user.setName("小紅");user.setEmail("test@ss8o.com"); ?int result = userMapper.update(user, queryWrapper);System.out.println(result > 0 ? "修改成功!" : "修改失敗!");System.out.println("受影響的行數為:" + result);} -
組裝select字句
執行SQL:SELECT username,age,email FROM t_user WHERE is_deleted=0
@Testpublic void test06(){//查詢用戶的用戶名、年齡、郵箱信息//SELECT name,age,email FROM t_user WHERE is_deleted=0QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.select("name","age","email");List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);maps.forEach(System.out::println);} -
實現子查詢
@Testpublic void test07(){//查詢id小于等于100的用戶信息//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (id IN (select id from t_user where id <= 100))QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.inSql("id", "select id from t_user where id <= 100");List<User> list = userMapper.selectList(queryWrapper);list.forEach(System.out::println);}
3.UpdateWrapper
UpdateWrapper不僅擁有QueryWrapper的組裝條件功能,還提供了set方法進行修改對應條件的數據庫信息
@Testpublic void test08(){//將用戶名中包含有a并且(年齡大于20或郵箱為null)的用戶信息修改//UPDATE t_user SET name=?,email=? WHERE is_deleted=0 AND (name LIKE ? AND (age > ? OR email IS NULL))UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();updateWrapper.like("name","a").and( i -> i.gt("age",20).or().isNull("email")).set("name","小黑").set("email","svip@qq.com");//設置修改的字段 ?int result = userMapper.update(null, updateWrapper);System.out.println(result > 0 ? "修改成功!" : "修改失敗!");System.out.println("受影響的行數為:" + result);}4.condition參數
滿足condition參數的條件就執行這個條件構造器中的條件
模擬開發中客戶端傳到服務器的參數就行測試
在真正開發的過程中,組裝條件是常見的功能,而這些條件數據來源于用戶輸入,是可選的,因此我們在組裝這些條件時,必須先判斷用戶是否選擇了這些條件,若選擇則需要組裝該條件,若沒有選擇(null)則一定不能組裝,以免影響SQL執行的結果
-
思路一 復雜寫法
執行SQL:SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (user_name LIKE ? AND age <= ?)
//復雜寫法,模擬開發中客戶端傳到服務器的參數就行測試@Testpublic void test09(){//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (name LIKE ? AND age <= ?)String username = "a";Integer ageBegin = null;Integer ageEnd = 30;QueryWrapper<User> queryWrapper = new QueryWrapper<>();if(StringUtils.isNotBlank(username)){//isNotBlank判斷某個字符創是否不為空字符串、不為null、不為空白符queryWrapper.like("name", username);}if(ageBegin != null){queryWrapper.ge("age", ageBegin);}if(ageEnd != null){queryWrapper.le("age", ageEnd);}List<User> list = userMapper.selectList(queryWrapper);list.forEach(System.out::println);} -
思路二 簡單寫法:使用condition參數
-
滿足condition參數的條件就執行這個條件構造器中的條件
-
上面的實現方案沒有問題,但是代碼比較復雜,我們可以使用帶condition參數的重載方法構建查詢條件,簡化代碼的編寫
//簡單寫法:使用condition參數@Testpublic void test10(){//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (name LIKE ? AND age <= ?)String username = "a";Integer ageBegin = null;Integer ageEnd = 30;QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.like(StringUtils.isNotBlank(username),"name",username).ge(ageBegin!=null,"age",20).le(ageEnd!=null,"age",20);List<User> list = userMapper.selectList(queryWrapper);list.forEach(System.out::println);}
5.LambdaQueryWrapper
功能等同于QueryWrapper,提供了Lambda表達式的語法可以避免填錯列名。通過屬性名自動匹配字段名
//LambdaQueryWrapper:提供了Lambda表達式的語法可以避免填錯列名。通過屬性名自動匹配字段名//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (name LIKE ? AND age <= ?)@Testpublic void test11(){String username = "a";Integer ageBegin = null;Integer ageEnd = 30;LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.like(StringUtils.isNotBlank(username),User::getName,username).ge(ageBegin!=null,User::getAge,20) //User::getAge:通過屬性名自動匹配字段名.le(ageEnd!=null,User::getAge,20);List<User> list = userMapper.selectList(queryWrapper);list.forEach(System.out::println);}6.LambdaUpdateWrapper
功能等同于UpdateWrapper,提供了Lambda表達式的語法可以避免填錯列名。
//LambdaUpdateWrapper:功能等同于UpdateWrapper,提供了Lambda表達式的語法可以避免填錯列名。 //UPDATE t_user SET name=?,email=? WHERE is_deleted=0 AND (name LIKE ? AND (age > ? OR email IS NULL))@Test public void test12(){//將用戶名中包含有a并且(年齡大于20或郵箱為null)的用戶信息修改LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.like(User::getName, "a").and(i -> i.gt(User::getAge, 20).or().isNull(User::getEmail));updateWrapper.set(User::getName, "小黑").set(User::getEmail,"abc@atguigu.com");int result = userMapper.update(null, updateWrapper);System.out.println("result:"+result); }六、常用插件
1.分頁插件
MyBatis Plus自帶分頁插件,只要簡單的配置即可實現分頁功能
-
導入mybatis-plus依賴
<!--mybatis-plus啟動器--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version> </dependency> ?<!-- 數據庫驅動 --> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version> </dependency> -
添加配置類MyBatisPlusConfig
@Configuration @MapperScan("com.atguigu.mybatisplus.mapper") public class MyBatisPlusConfig {//配置MybatisPlus的插件的 Interceptor:攔截器@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加分頁插件 DbType:數據庫類型interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;} } -
編寫測試方法
@Test public void testPage(){//new Page()中的兩個參數分別是當前頁碼,每頁顯示數量//SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 LIMIT ?,?Page<User> page = new Page<>(2,2);Page<User> userPage = userMapper.selectPage(page, null); ?System.out.println(userPage);List<User> users = page.getRecords();//分頁后的數據users.forEach(System.out::println); ?System.out.println("總頁數:"+userPage.getPages());System.out.println("總條數:"+userPage.getTotal());System.out.println("當前頁:"+userPage.getCurrent());System.out.println("當前頁顯示條數:"+userPage.getSize());System.out.println("是否有下一頁:"+userPage.hasNext());System.out.println("是否有上一頁:"+userPage.hasPrevious()); }
2.自定義分頁
上面調用的是MyBatis-Plus提供的帶有分頁的方法,那么我們自己定義的方法如何實現分頁呢?
-
在UserMapper接口中定義一個方法
/*** 根據年齡大于20的用戶查詢用戶列表,分頁顯示 * @param page 分頁對象,xml中可以從里面進行取值,傳遞參數 Page 即自動分頁,必須放在第一位 * @param age 年齡 * @return */ Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age); -
在UserMapper.xml中編寫SQL實現該方法
<select id="selectPageVo" resultType="User">select id,username as name,age,email from t_user where age > #{age} </select> -
編寫測試方法
@Test public void testPageVo(){Page<User> page = userMapper.selectPageVo(new Page<User>(1,2), 20);List<User> users = page.getRecords();users.forEach(System.out::println); }第二種寫法
//自定義分頁 根據年齡大于20的用戶查詢用戶列表,分頁顯示 @Test public void testPageVo(){Page<User> page = new Page<>(1,2);QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.gt("age",20);userMapper.selectPage(page,queryWrapper);List<User> users = page.getRecords();users.forEach(System.out::println); }
3.樂觀鎖
作用:當要更新一條記錄的時候,希望這條記錄沒有被別人更新
樂觀鎖的實現方式:
-
取出記錄時,獲取當前 version
-
更新時,帶上這個 version
-
執行更新時, UPDATE t_product SET name=?, price=100+50, version(更改后的新值+1)=1 WHERE id=? AND version(舊值)=0。
-
滿足條件,newVersion: oldVersion 舊值每次都會+1
-
如果 version 不對,就更新失敗
3.1 場景
-
一件商品,成本價是80元,售價是100元。老板先是通知小李,說你去把商品價格增加50元。小李正在玩游戲,耽擱了一個小時。正好一個小時后,老板覺得商品價格增加到150元,價格太高,可能會影響銷量。又通知小王,你把商品價格降低30元。
-
此時,小李和小王同時操作商品后臺系統。小李操作的時候,系統先取出商品價格100元;小王也在操作,取出的商品價格也是100元。小李將價格加了50元,并將100+50=150元存入了數據庫;小王將商品減了30元,并將100-30=70元存入了數據庫。是的,如果沒有鎖,小李的操作就完全被小王的覆蓋了。
-
現在商品價格是70元,比成本價低10元。幾分鐘后,這個商品很快出售了1千多件商品,老板虧1萬多。
3.2 樂觀鎖與悲觀鎖
-
上面的故事,如果是樂觀鎖,小王保存價格前,會檢查下價格是否被人修改過了。如果被修改過了,則重新取出的被修改后的價格,150元,這樣他會將120元存入數據庫。
-
如果是悲觀鎖,小李取出數據后,小王只能等小李操作完之后,才能對價格進行操作,也會保證最終的價格是120元。
3.3 模擬修改沖突
-
數據庫中增加商品表
CREATE TABLE t_product ( id BIGINT(20) NOT NULL COMMENT '主鍵ID', NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名稱', price INT(11) DEFAULT 0 COMMENT '價格', VERSION INT(11) DEFAULT 0 COMMENT '樂觀鎖版本號', PRIMARY KEY (id) ); -
添加一條數據
INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人筆記本', 100); -
添加一個實體類Product
@Data public class Product {private Long id;private String name;private Integer price;private Integer version; } -
添加一個Mapper接口ProductMapper
public interface ProductMapper extends BaseMapper<Product> {} -
測試方法
? ?//模擬修改沖突@Testpublic void testProduct01(){//1.小李獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productLi = productMapper.selectById(1);System.out.println("小李獲取的商品價格為:" + productLi.getPrice());//100 ?//2.小王獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productWang = productMapper.selectById(1);System.out.println("小王獲取的商品價格為:" + productWang.getPrice());//100 ?//3.小李修改商品價格+50productLi.setPrice(productLi.getPrice()+50);//UPDATE t_product SET name=?, price=100+50, version=? WHERE id=?productMapper.updateById(productLi);//100+50=150 ?//4.小王修改商品價格-30productWang.setPrice(productWang.getPrice()-30);//UPDATE t_product SET name=?, price=100-30, version=? WHERE id=?productMapper.updateById(productWang);//100-30=70 ?//5.老板查詢商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productBoss = productMapper.selectById(1);System.out.println("老板獲取的商品價格為:" + productBoss.getPrice());//70} -
執行結果
3.4 樂觀鎖解決問題
-
實體類version字段添加注解@Version
@Data public class Product {private Long id;private String name;private Integer price;@Version //標識樂觀鎖版本號字段private Integer version; } -
添加樂觀鎖插件配置
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();//添加分頁插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//添加樂觀鎖插件interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return interceptor; } -
再次執行測試方法,樂觀鎖測試
小李查詢商品信息:
SELECT id,name,price,version FROM t_product WHERE id=?
小王查詢商品信息:
SELECT id,name,price,version FROM t_product WHERE id=?
小李修改商品價格,自動將version+1
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人筆記本(String), 150(Integer), 1(Integer), 1(Long), 0(Integer)
小王修改商品價格,此時version已更新,條件不成立,修改失敗
UPDATE t_product SET name=?, price=?, version=? WHERE id=? AND version=?
Parameters: 外星人筆記本(String), 70(Integer), 1(Integer), 1(Long), 0(Integer)
最終,小王修改失敗,查詢價格:150
SELECT id,name,price,version FROM t_product WHERE id=?
- //樂觀鎖測試 @Test public void testProduct02(){//1.小李獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productLi = productMapper.selectById(1);System.out.println("小李獲取的商品價格為:" + productLi.getPrice());//100 ?//2.小王獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productWang = productMapper.selectById(1);System.out.println("小王獲取的商品價格為:" + productWang.getPrice());//100 ?//3.小李修改商品價格+50productLi.setPrice(productLi.getPrice()+50);//100+50=150//UPDATE t_product SET name=?, price=100+50, version=1 WHERE id=? AND version=0productMapper.updateById(productLi);//現在版本號已經變成1了 ?//4.小王修改商品價格-30productWang.setPrice(productWang.getPrice()-30); //100-30=70//UPDATE t_product SET name=?, price=100-30, version=1 WHERE id=? AND version=0productMapper.updateById(productWang);//現在版本號已經變成1了,所以這里沒有修改成功 ?//5.老板查詢商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productBoss = productMapper.selectById(1);System.out.println("老板獲取的商品價格為:" + productBoss.getPrice());//150 }
-
優化執行流程
?//優化樂觀鎖測試@Testpublic void testProduct03(){//1.小李獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productLi = productMapper.selectById(1);System.out.println("小李獲取的商品價格為:" + productLi.getPrice());//100 ?//2.小王獲取商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productWang = productMapper.selectById(1);System.out.println("小王獲取的商品價格為:" + productWang.getPrice());//100 ?//3.小李修改商品價格+50productLi.setPrice(productLi.getPrice()+50);//100+50=150//UPDATE t_product SET name=?, price=100+50, version=1 WHERE id=? AND version=0productMapper.updateById(productLi);//現在版本號已經變成1了 ?//4.小王修改商品價格-30productWang.setPrice(productWang.getPrice()-30); //100-30=70//UPDATE t_product SET name=?, price=100-30, version=1 WHERE id=? AND version=0int result = productMapper.updateById(productWang);//現在版本號已經變成1了,所以這里沒有修改成功if(result == 0){//操作失敗,重試//重新查詢一次,這是小李修改玩的數據Product productNew = productMapper.selectById(1);//再次更新,現在價格是150-30productNew.setPrice(productNew.getPrice()-30);//再次修改productMapper.updateById(productNew);} ?//5.老板查詢商品價格//SELECT id,name,price,version FROM t_product WHERE id=?Product productBoss = productMapper.selectById(1);System.out.println("老板獲取的商品價格為:" + productBoss.getPrice());//120}
七、通用枚舉
表中的有些字段值是固定的,例如性別(男或女),此時我們可以使用MyBatis-Plus的通用枚舉來實現
-
數據庫表添加字段sex
-
創建通用枚舉類型
@Getter public enum SexEnum {MALE(1, "男"),FEMALE(2, "女"); ?@EnumValue //將注解所標識的屬性的值存儲到數據庫中private int sex;private String sexName; ?SexEnum(Integer sex, String sexName) {this.sex = sex;this.sexName = sexName;} } -
User實體類中添加屬性sex
public class User {private Long id;@TableField("username")private String name;private Integer age;private String email; ?@TableLogicprivate int isDeleted; ?//邏輯刪除 ?private SexEnum sex; } -
配置掃描通用枚舉
#MyBatis-Plus相關配置 mybatis-plus:#指定mapper文件所在的地址mapper-locations: classpath:mapper/*.xmlconfiguration:#配置日志log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:banner: offdb-config:#配置mp的主鍵策略為自增id-type: auto# 設置實體類所對應的表的統一前綴table-prefix: t_#配置類型別名所對應的包type-aliases-package: com.atguigu.mybatisplus.pojo# 掃描通用枚舉的包type-enums-package: com.atguigu.mybatisplus.enums -
執行測試方法
@Test public void test(){User user = new User();user.setName("admin");user.setAge(33);user.setSex(SexEnum.MALE);int result = userMapper.insert(user);System.out.println("result:"+result); }
八、代碼生成器
1、引入依賴
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId>//代碼生成器的核心依賴<version>3.5.1</version> </dependency> <dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId>//freemarker引擎模板依賴<version>2.3.31</version> </dependency>2、快速生成
public class FastAutoGeneratorTest { ?public static void main(String[] args) {FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/mybatis_plus?characterEncoding=utf-8&userSSL=false", "root", "123456").globalConfig(builder -> {builder.author("atguigu") // 設置作者//.enableSwagger() // 開啟 swagger 模式.fileOverride() // 覆蓋已生成文件.outputDir("D://mybatis_plus"); // 指定輸出目錄}).packageConfig(builder -> {builder.parent("com.atguigu") // 設置父包名.moduleName("mybatisplus") // 設置父包模塊名// 設置mapperXml映射文件生成路徑.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus"));}).strategyConfig(builder -> {builder.addInclude("t_user") // 設置需要生成的表名.addTablePrefix("t_", "c_"); // 設置過濾表前綴}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默認的是Velocity引擎模板.execute();} }九、多數據源
適用于多種場景:純粹多庫、 讀寫分離、 一主多從、 混合模式等
場景說明:
我們創建兩個庫,分別為:mybatis_plus(以前的庫不動)與mybatis_plus_1(新建),將mybatis_plus庫的product表移動到mybatis_plus_1庫,這樣每個庫一張表,通過一個測試用例分別獲取用戶數據與商品數據,如果獲取到說明多庫模擬成功
1.創建數據庫及表
-
創建數據庫mybatis_plus_1和表`product
CREATE DATABASE `mybatis_plus_1` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; use `mybatis_plus_1`; CREATE TABLE product ( id BIGINT(20) NOT NULL COMMENT '主鍵ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '商品名稱', price INT(11) DEFAULT 0 COMMENT '價格', version INT(11) DEFAULT 0 COMMENT '樂觀鎖版本號', PRIMARY KEY (id) ); -
添加測試數據
INSERT INTO product (id, NAME, price) VALUES (1, '外星人筆記本', 100); -
刪除mybatis_plus庫中的product表
use mybatis_plus; DROP TABLE IF EXISTS product;
2.新建工程引入依賴
自行新建一個Spring Boot工程并選擇MySQL驅動及Lombok依賴
引入多數據源的依賴
<dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version> </dependency>3.編寫配置文件
spring:# 配置數據源信息datasource:dynamic:# 設置默認的數據源或者數據源組,默認值即為masterprimary: master# 嚴格匹配數據源,默認false.true未匹配到指定數據源時拋異常,false使用默認數據源strict: false# 配置多數據源信息datasource:#主數據源master:url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456#從數據源slave_1:url: jdbc:mysql://localhost:3306/mybatis_plus_1?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 1234564.創建實體類
-
新建一個User實體類(如果數據庫表名有t_前綴記得配置)
@Data @TableName("t_user")//指定表 public class User { ?private Long id; ?private String name; ?private Integer age; ?private Integer sex; ?private String email; ?private Integer isDeleted; } -
新建一個實體類Product
@Data @AllArgsConstructor @NoArgsConstructor public class Product { ?private Long id; ?private String name; ?private Integer price; ?private Integer version; }
5.創建Mapper及Service
-
新建接口UserMapper
@Repository public interface UserMapper extends BaseMapper<User> {} -
新建接口ProductMapper
@Repository public interface ProductMapper extends BaseMapper<Product> {} -
新建Service接口UserService指定操作的數據源
public interface UserService extends IService<User> {} -
新建Service接口ProductService指定操作的數據源
public interface ProductService extends IService<Product> {} -
建立UserService的實現類
@Service @DS("master")//多數據源操作,指定要操作的數據源,master指定的是mybatis_plus數據庫里面有t_user表,不寫注解使用默認數據源 public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }建立ProductService的實現類
@Service @DS("slave_1")//多數據源操作,指定要操作的數據源,slave_1指定的是mybatis_plus1數據庫里面有product表,不寫注解使用默認數據源 public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService{ ? }
6.編寫測試方法
記得在啟動類中添加注解@MapperScan()
class TestDatasourceApplicationTests {@ResourceUserService userService; ?@ResourceProductService productService; ?@Testvoid contextLoads() {User user = userService.getById(1L);Product product = productService.getById(1L);System.out.println("User = " + user);System.out.println("Product = " + product);} ? }十、MyBatisX插件
MyBatis-Plus為我們提供了強大的mapper和service模板,能夠大大的提高開發效率。
但是在真正開發過程中,MyBatis-Plus并不能為我們解決所有問題,例如一些復雜的SQL,多表聯查,我們就需要自己去編寫代碼和SQL語句,我們該如何快速的解決這個問題呢,這個時候可以使用MyBatisX插件。
MyBatisX一款基于 IDEA 的快速開發插件,為效率而生。
1.安裝MyBatisX插件
打開IDEA,File-> Setteings->Plugins->MyBatisX,搜索欄搜索MyBatisX然后安裝。
2.快速生成代碼
-
新建一個Spring Boot項目引入依賴(創建工程時記得勾選lombok及mysql驅動)
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version> </dependency> ? <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version> </dependency> -
配置數據源信息
spring:#配置數據庫datasource:# 配置連接數據庫信息driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8username: rootpassword: 123456 -
在IDEA中與數據庫建立鏈接
-
填寫數據庫信息并保存
-
?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false?
-
找到我們需要生成的表點擊右鍵
-
填寫完信息以后下一步
-
繼續填寫信息
-
大功告成(真特么好用yyds)
3.快速生成CRUD
MyBaitsX可以根據我們在Mapper接口中輸入的方法名快速幫我們生成對應的sql語句
public interface UserMapper extends BaseMapper<User> { ?//mybatisX快速生成CRUD 方法名都是見名實意//增加int insertSelective(User user); ?//刪除 通過id和年齡和姓名刪除int deleteByIdAndAgeAndName(@Param("id") Long id, @Param("age") Integer age, @Param("name") String name); ?//修改 通過id修改年齡跟性別int updateAgeAndSexById(@Param("age") Integer age, @Param("sex") Integer sex, @Param("id") Long id); ?//查詢 通過開始年齡和結束年齡查詢年齡和性別List<User> selectAgeAndSexByAgeBetween(@Param("beginAge") Integer beginAge, @Param("endAge") Integer endAge); ?//查詢全部List<User> selectAll(); ?//通過年齡降序查詢全部List<User> selectAllOrderByAgeDesc(); } ?測試
@SpringBootTest class Boot04MybatisxDemoApplicationTests { ?@AutowiredUserMapper userMapper; ?@Testvoid contextLoads() {List<User> users = userMapper.selectAll();System.out.println(users);List<User> users1 = userMapper.selectAgeAndSexByAgeBetween(10, 20);System.out.println(users1);} ? }總結
以上是生活随笔為你收集整理的Mybatis-Plus 新手入门,一篇足以的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 织梦后台发布文章编辑器不显示的解决办法
- 下一篇: 机械臂运动学入门(二)