MyBatis-Plus入門及基本用法
MyBatis-Plus入門及基本用法
需要的基礎:學習過MyBatis、Spring、SpringMVC就可以學習這個了!
為什麼需要學習它呢?MyBatis-Plus可以節約大量的工作時間,基本的CRUD可以自動化完成!
JPA、tk-mapper、MyBatis-Plus
簡介
是什麼?MyBatis-Plus就是簡化JDBC操作的!
官網:https://mp.baomidou.com/ 簡化MyBatis!
特性
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 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 操作智慧分析阻斷,也可自定義攔截規則,預防誤操作
快速入門
地址:https://mp.baomidou.com/guide/quick-start.html#初始化工程
使用第三方元件:
- 匯入相應的依賴
- 研究依賴如何配置
- 程式碼如何編寫
- 拓展技術能力
步驟
1、建立資料庫 mybatis_plus
2、建立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, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
--真實開發中,需要很多欄位,例如version(樂觀鎖)、deleted(邏輯刪除)、create_time、update_time
3、編寫專案,初始化專案!使用Springboot初始化!
4、匯入依賴
<!-- mysql驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus為個人開發,並非官方的-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
說明:我們使用mybatis-plus可以節省我們大量的程式碼,儘量不要同時匯入mybatis和mybatis-plus
5、連線資料庫,這一步和mybatis相同!
#myql5 與mysql8驅動不同,同時mysql8需要增加時區的配置
#mysql5為:com.mysql.jdbc.Driver,mysql8為:com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456qaz
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
傳統方式:pojo-dao(連線mybatis,配置mapper.xml檔案)-service-controller
6、使用mybatis-plus之後
-
pojo
@Data //有參建構函式 @AllArgsConstructor //無參建構函式 @NoArgsConstructor public class User { private Long id; private String name; private int age; private String email; }
-
mapper介面
package com.lin.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.lin.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; //代表持久層 @Repository @Mapper //在對應的Mapper上面繼承基本的類BaseMapper public interface UserMapper extends BaseMapper<User> { }
注意點:我們需要在主啟動類上掃描我們的mapper包下的所有介面@MapperScan("com.lin.mapper")
- 測試類中測試
@SpringBootTest
class MybatisPlusApplicationTests {
//繼承了BaseMapper,所有的方法都來自父類
//可以編寫自己的拓展方法
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//引數是一個wrapper,條件構造器,可以傳null,查詢全部使用者
List<User> users = userMapper.selectList(null);
//第一種
users.forEach(System.out::println);
//第二種
users.forEach(user -> System.out.println(user));
//第三種
for(User user : users) {
System.out.println(user);
}
}
}
-
結果
配置日誌
我們所有的sql現在是不可見的,我們希望知道它是怎麼執行的,所以我們必須要看日誌!
#日誌配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD拓展
插入操作
@Test
public void testInsert() {
User user = new User();
user.setName("林先生");
user.setAge(12);
user.setEmail("[email protected]");
//幫我們自動生成id
int insert = userMapper.insert(user);
//受影響的行數
System.out.println(insert);
//自動回填id
System.out.println(user);
}
資料庫插入的id的預設值為:全域性的唯一id
主鍵生成策略
預設 IdType.ID_WORKER 全域性唯一id
分散式系統唯一id生成參考部落格:https://www.cnblogs.com/haoxinyue/p/5208136.html
雪花演算法:
snowflake是Twitter開源的分散式ID生成演算法,結果是一個long型的ID。其核心思想是:使用41bit作為毫秒數,10bit作為機器的ID(5個bit是資料中心,5個bit的機器ID),12bit作為毫秒內的流水號(意味著每個節點在每毫秒可以產生 4096 個 ID),最後還有一個符號位,永遠是0。
主鍵自增
- 實體類欄位上 @TableId(type = IdType.AUTO)
- 資料庫欄位一定要自增
其餘的原始碼解釋
public enum IdType {
AUTO(0),//資料庫id自增
NONE(1),//未設定主鍵
INPUT(2),//手動輸入
ID_WORKER(3),//預設的全域性唯一id
UUID(4),//全域性唯一id
ID_WORKER_STR(5);//ID_WORKER的字串表示法
更新操作
@Test
public void testUpdate() {
User user = new User();
//通過條件自動拼接動態sql
user.setAge(15);
user.setName("和跳跳");
user.setId(5L);
//主義:updateByid 引數是一個物件
userMapper.updateById(user);
}
所有的sql都是自動配置的!
自動填充策略
建立時間、修改時間!這些操作一般都是自動化完成的,我們不希望手動更新!
阿里巴巴開發手冊:所有的資料庫表:gmt_create、gmt_modified幾乎所有的表都要配置上,而且需要自動化!
資料庫級別(工作中一般不能修改資料庫)
1、在表中新增欄位create_time、update_time
alter table user modify column create_time datetime not null default current_timestamp
alter table user modify column update_time datetime not null default current_timestamp on update current_timestamp;
2、再次測試插入方法,再次之前需要同步實體類!
private Date create_time;
private Date update_time;
3、測試結果如下:
程式碼級別
1、刪除資料庫的預設值及更新操作
2、實體類屬性上添加註解!
@TableField(fill = FieldFill.INSERT)
private Date create_time;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date update_time;
3、編寫處理器處理這個這個註解即可!
package com.lin.handle;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
@Slf4j//lombok的日誌,也可以使用springboot自帶的日誌
@Component//不要忘記把處理器加入到ioc容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入時的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill...");
this.setFieldValByName("create_time", new Date(),metaObject);
this.setFieldValByName("update_time",new Date(),metaObject);
}
//更新時的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill...");
this.setFieldValByName("update_time",new Date(),metaObject);
}
}
4、結果如下:
樂觀鎖
在面試過程中,經常會被問到樂觀鎖以及悲觀鎖的機制。
- 樂觀鎖:顧名思義十分樂觀,它總是認為不會出現問題,無論幹什麼都不會去上鎖!如果出現了問題,再次更新值測試。
- 悲觀鎖:顧名思義十分悲觀,它總是認為會出現問題,無論幹什麼都會去上鎖!上鎖後再進行操作。
樂觀鎖實現方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
--A執行緒
update user set name = ‘琳’ and version = version + 1
where id = 2 and version = 1;
--B執行緒搶先A執行緒完成更新操作,這個時候version = 2,導致A執行緒更新失敗
update user set name = ‘哈哈’ and version = version + 1
where id = 2 and version = 1;
測試MyBatis-Plus的樂觀鎖外掛:
1、給資料庫加上version欄位:
alter table user add column version integer not null default 1 comment '版本號';
2、實體類加對應的欄位
@Version//樂觀鎖的Version註解
private Integer version;
3、註冊元件
//不在啟動類配置時,需要在此配置
@MapperScan("com.lin.mapper")
//預設開啟事務管理
@EnableTransactionManagement
//整合第三方元件時需要新增此註解,表示配置類,@Bean搭配裝配Bean
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4、測試:
//測試樂觀鎖成功
@Test
public void testOptimisticLocker(){
//查詢
User user = userMapper.selectById(4L);
//修改
user.setEmail("[email protected]");
//更新
userMapper.updateById(user);
}
//測試樂觀鎖失敗
@Test
public void testOptimisticLocker2(){
//模擬執行緒1
User user = userMapper.selectById(4L);
user.setEmail("[email protected]");
//模擬執行緒2,執行緒2搶先更新操作
User user1 = userMapper.selectById(4L);
user1.setEmail("[email protected]");
userMapper.updateById(user1);
//執行緒1無法提交更新操作,如果沒有樂觀鎖則會覆蓋執行緒2提交的值
//自旋鎖多次嘗試提交
userMapper.updateById(user);
}
5、結果如下:
查詢操作
//測試查詢
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
//測試批量查詢
@Test
public void testSelectBatchById() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L));
users.forEach(System.out::println);
}
//條件查詢map
@Test
public void testSelectBatchByIds() {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("name", "和跳跳");
hashMap.put("age", 15);
List<User> users = userMapper.selectByMap(hashMap);
}
分頁查詢
- 原始的limit進行分頁
- PageHelper第三方外掛
- MyBatis-Plus也有內建外掛
1、配置攔截器元件
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設定請求的頁面大於最大頁後操作, true調回到首頁,false 繼續請求 預設false
// paginationInterceptor.setOverflow(false);
// 設定最大單頁限制數量,預設 500 條,-1 不受限制
// paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
2、直接使用page物件
//測試分頁查詢
@Test
public void testPage() {
//建立Page物件
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
刪除操作
基本的刪除操作
@Test
public void testDeleteById() {
userMapper.deleteById(1294183513728778242L);
}
@Test
public void testDeleteBatchById() {
userMapper.deleteBatchIds(Arrays.asList(1294183513728778243L,1294183513728778244L));
}
@Test
public void tesetDeleteBatchByIds() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "林先生");
userMapper.deleteByMap(map);
}
邏輯刪除
邏輯刪除即不會刪除資料庫資料,對應資料的deleted = 0變成 deleted = 1狀態的變化
1、資料庫新增欄位deleted
alter table user add column deleted integer not null default 0 comment '刪除狀態'
2、實體類新增相應欄位
@TableLogic
private Integer deleted;
3、配置(3.1.1以上版本不需要配置)
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
properties如下:
#已刪除值為1
mybatis-plus.global-config.db-config.logic-delete-value=1
#未刪除值為0
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4、測試結果如下:
條件構造器
//isNotNull、ge、between
@Test
public void testWrapper1() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.isNotNull("name").ge("age", 15).between("create_time", "2019-09-08 00:00:00", "2020-08-24 00:00:00");
userMapper.selectList(userQueryWrapper).forEach(System.out::println);
}
//eq、lt
@Test
public void testWrapper2() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("name", "琳姑姑").lt("age", 100);
System.out.println(userMapper.selectOne(userQueryWrapper));
System.out.println(userMapper.selectCount(userQueryWrapper));
}
//notLike、likeLeft
@Test
public void testWrapper3() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
userQueryWrapper.notLike("name", "姑姑").likeLeft("name", "跳跳");
List<Map<String, Object>> maps = userMapper.selectMaps(userQueryWrapper);
maps.forEach(System.out::println);
}
//inSql
@Test
public void testWrapper4() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
userQueryWrapper.inSql("id", "select id from user where id < 5");
List<Object> objects = userMapper.selectObjs(userQueryWrapper);
objects.forEach(System.out::println);
}
//orderBy
@Test
public void testWrapper5() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
userQueryWrapper.orderByDesc("id").orderByAsc("age");
List<Object> objects = userMapper.selectObjs(userQueryWrapper);
objects.forEach(System.out::println);
}
程式碼自動生成器
AutoGenerator 是 MyBatis-Plus 的程式碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模組的程式碼,極大的提升了開發效率。
引入依賴:
<!-- mybatis-plus程式碼生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
編寫生成器:
package com.lin.config;
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 java.util.ArrayList;
public class MyBatisAutoGenerator {
public static void main(String[] args) {
//程式碼生成器
AutoGenerator autoGenerator = new AutoGenerator();
//全域性配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setAuthor("LinXianSheng");
//時間型別
globalConfig.setDateType(DateType.ONLY_DATE);
//ID增長
globalConfig.setIdType(IdType.AUTO);
//開啟檔案目錄
globalConfig.setOpen(false);
//Swagger2
globalConfig.setSwagger2(true);
//是否覆蓋原有檔案
globalConfig.setFileOverride(false);
//檔案輸出目錄
String projectPath = System.getProperty("user.dir");
globalConfig.setOutputDir(projectPath + "/src/main/java");
autoGenerator.setGlobalConfig(globalConfig);
//資料來源配置
DataSourceConfig dataSourceConfig = new DataSourceConfig();
//資料庫型別
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("123456");
//驅動名稱
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
autoGenerator.setDataSource(dataSourceConfig);
//包配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setController("controller");
packageConfig.setEntity("entity");
packageConfig.setService("service");
packageConfig.setMapper("mapper");
packageConfig.setParent("com.lin");
packageConfig.setModuleName("blog");
autoGenerator.setPackageInfo(packageConfig);
//策略配置
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setLogicDeleteFieldName("deleted");
strategyConfig.setVersionFieldName("version");
strategyConfig.setInclude("user");
//生成@RestController
strategyConfig.setRestControllerStyle(true);
//生成lombok
strategyConfig.setEntityLombokModel(true);
//駝峰轉連字元,localhost:8080/hello_id_10,即訪問帶下劃線引數
strategyConfig.setControllerMappingHyphenStyle(true);
//自動填充設定
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(createTime);
tableFills.add(updateTime);
strategyConfig.setTableFillList(tableFills);
autoGenerator.setStrategy(strategyConfig);
//執行
autoGenerator.execute();
}
}
生成結果如下: