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, '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');
--真實開發中,需要很多字段,例如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("023023@qq.com");
//幫我們自動生成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 add column create_time datetime not null default current_timestamp
alter table user add 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("233823@qq.com");
//更新
userMapper.updateById(user);
}
//測試樂觀鎖失敗
@Test
public void testOptimisticLocker2(){
//模擬線程1
User user = userMapper.selectById(4L);
user.setEmail("233823@qq.com");
//模擬線程2,線程2搶先更新操作
User user1 = userMapper.selectById(4L);
user1.setEmail("e9234823@qq.com");
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();
}
}
生成結果如下: