@
一、MyBatis-Plus簡介
MyBatis-Plus (簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

MyBatis-Plus具有如下特性:
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
二、基本用法
1、准備數據
我們這里使用MySQL數據庫,先准備好相關數據
表結構:其中種類和產品是一對多的關系

建表語句:
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '種類表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`category_id` int(11) NOT NULL,
`price` decimal(10, 2) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
2、引入依賴
通過開發工具創建一個SpringBoot項目(版本為2.4.0),引入以下依賴:
<!--mybatis-plus依賴-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、配置
在配置文件里寫入相關配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
在 Spring Boot 啟動類中添加 @MapperScan 注解,掃描 Mapper 文件夾:
@SpringBootApplication
@MapperScan("cn.fighter3.mapper")
public class SpringbootMybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisPlusApplication.class, args);
}
}
3、代碼
- 實體類
/**
* @Author 三分惡
* @Date 2020/11/14
* @Description 產品實體類
*/
@TableName(value = "product")
public class Product {
@TableId(type = IdType.AUTO)
private Long pid;
private String productName;
private Long categoryId;
private Double price;
//省略getter、setter
}
- Mapper接口:繼承BaseMapper即可
/**
* @Author 三分惡
* @Date 2020/11/14
* @Description
*/
public interface ProductMapper extends BaseMapper<Product> {
}
4、測試
- 添加測試類
@SpringBootTest
class SpringbootMybatisPlusApplicationTests {
}
- 插入
@Test
@DisplayName("插入數據")
public void testInsert(){
Product product=new Product();
product.setProductName("小米10");
product.setCategoryId(1l);
product.setPrice(3020.56);
Integer id=productMapper.insert(product);
System.out.println(id);
}
- 根據id查找
@Test
@DisplayName("根據id查找")
public void testSelectById(){
Product product=productMapper.selectById(1l);
System.out.println(product.toString());
}
- 查找所有
@Test
@DisplayName("查找所有")
public void testSelect(){
List productList=productMapper.selectObjs(null);
System.out.println(productList);
}
- 更新
@Test
@DisplayName("更新")
public void testUpdate(){
Product product=new Product();
product.setPid(1l);
product.setPrice(3688.00);
productMapper.updateById(product);
}
- 刪除
@Test
@DisplayName("刪除")
public void testDelete(){
productMapper.deleteById(1l);
}
三、自定義SQL
使用MyBatis的主要原因是因為MyBatis的靈活,mp既然是只對MyBatis增強,那么自然也是支持以Mybatis的方式自定義sql的。
- 修改pom.xml,在 <build>中添加:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
- 配置文件:添加mapper掃描路徑及實體類別名包
mybatis.mapper-locations=classpath:cn/fighter3/mapper/*.xml
mybatis.type-aliases-package=cn.fighter3.model
1、自定義批量插入
批量插入是比較常用的插入,BaseMapper中並沒有默認實現,在com.baomidou.mybatisplus.service.IService中雖然實現了,但是是一個循環的插入。
所以用Mybatis的方式自定義一個:
- 在ProductMapper同級路徑下新建ProductMapper:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.fighter3.mapper.ProductMapper">
</mapper>
- 在接口里定義批量插入方法
public interface ProductMapper extends BaseMapper<Product> {
void batchInsert(@Param("productList") List<Product> productList);
}
- 編寫批量插入xml腳本
<insert id="batchInsert">
insert into product (product_name,category_id,price)
values
<foreach collection="productList" item="product" separator=",">
(#{product.productName},#{product.categoryId},#{product.price})
</foreach>
</insert>
- 測試
@Test
public void testBatchInsert(){
List<Product> productList=new ArrayList<>();
productList.add(new Product("小米10",1l,3020.56));
productList.add(new Product("Apple iPhone 11",1l,4999.00));
productList.add(new Product("Redmi 8A",1l,699.00));
productList.add(new Product("華為 HUAWEI nova 5z",1l,1599.00));
productList.add(new Product("OPPO A52",1l,1399.00));
productMapper.batchInsert(productList);
}
2、自定義查詢
基本的Mybatis方式的查詢這里就不再展示了,參照Mybatis的即可。
MP提供了一種比較方便的查詢參數返回和查詢條件參數傳入的機制。
2.1、自定義返回結果
Mybatis Plus接口里定義的查詢是可以直接以map的形式返回。
- 定義:定義了一個方法,返回用的是map
/**
* 返回帶分類的產品
* @return
*/
List<Map> selectProductWithCategory();
- 查詢腳本:查詢字段有pid、product_name、category_name、price
<select id="selectProductWithCategory" resultType="map">
select p.pid,p.product_name,c.category_name,p.price from product p left join category c on p.category_id=c.cid
</select>
- 測試:
@Test
@DisplayName("自定義返回結果")
public void testsSlectProductWithCategory(){
List<Map> productList=productMapper.selectProductWithCategory();
productList.stream().forEach(item->{
System.out.println(item.toString());
});
}
- 結果:

2.2、自定義查詢條件參數
除了返回結果可以使用map,查詢用的參數同樣可以用map來傳入。
- 定義:
List<Map> selectProductWithCategoryByMap(Map<String,Object> map);
- 查詢腳本:
<select id="selectProductWithCategoryByMap" resultType="map" parameterType="map">
select p.pid,p.product_name,c.category_name,p.price from product p left join category c on p.category_id=c.cid
<where>
<if test="categoryId !=null and categoryId !=''">
and p.category_id=#{categoryId}
</if>
<if test="pid !=null and pid !=''">
and p.pid=#{pid}
</if>
</where>
</select>
- 測試:
@Test
@DisplayName("自定義返回結果有入參")
public void testSelectProductWithCategoryByMap(){
Map<String,Object> params=new HashMap<>(4);
params.put("categoryId",1l);
params.put("pid",5);
List<Map> productList=productMapper.selectProductWithCategoryByMap(params);
productList.stream().forEach(item->{
System.out.println(item.toString());
});
}
- 結果:

2.3、map轉駝峰
上面查詢結果可以看到,返回的確實是map,沒有問題,但java類中的駝峰沒有轉回來呀,這樣就不友好了。
只需要一個配置就能解決這個問題。
創建 MybatisPlusConfig.java 配置類,添加上下面配置即可實現map轉駝峰功能。
/**
* @Author 三分惡
* @Date 2020/11/16
* @Description
*/
@Configuration
@MapperScan("cn.fighter.mapper")
public class MybatisPlusConfig {
@Bean("mybatisSqlSession")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
configuration.setJdbcTypeForNull(JdbcType.NULL);
//*注冊Map 下划線轉駝峰*
configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
// 添加數據源
sqlSessionFactory.setDataSource(dataSource);
sqlSessionFactory.setConfiguration(configuration);
return sqlSessionFactory.getObject();
}
}
再次運行之前的單元測試,結果:

OK,下划線已經轉駝峰了。
3、自定義一對多查詢
在實際應用中我們常常需要用到級聯查詢等查詢,可以采用Mybatis的方式來實現。
3.1、 Category相關
category和product是一對多的關系,我們這里先把category表相關的基本實體、接口等編寫出來。
- Category.java
/**
* @Author 三分惡
* @Date 2020/11/15
* @Description
*/
@TableName(value = "category")
public class Category {
@TableId(type = IdType.AUTO)
private Long id;
private String categoryName;
private List<Product> productList;
//省略getter、setter等
}
- CategoryMapper.java
/**
* @Author 三分惡
* @Date 2020/11/15
* @Description
*/
public interface CategoryMapper extends BaseMapper<Category> {
}
- CategoryMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.fighter3.mapper.CategoryMapper">
</mapper>
直接向數據庫中插入數據:
INSERT into category(category_name) VALUE ('手機');
3.2、自定義返回結果
自定義返回結果map:
<!--自定義返回列-->
<resultMap id="categoryAndProduct" type="cn.fighter3.model.Category">
<id column="cid" property="cid" />
<result column="category_name" property="categoryName" />
<!--一對多關系-->
<!-- property: 指的是集合屬性的值, ofType:指的是集合中元素的類型 -->
<collection property="productList" ofType="cn.fighter3.model.Product">
<id column="pid" property="pid" />
<result column="product_name" property="productName" />
<result column="category_id" property="categoryId" />
<result column="price" property="price" />
</collection>
</resultMap>
3.3、自定義一對多查詢
- 先定義方法
public interface CategoryMapper extends BaseMapper<Category> {
List<Category> selectCategoryAndProduct(Long id);
}
- 查詢腳本
<!--查詢分類下的產品-->
<select id="selectCategoryAndProduct" resultMap="categoryAndProduct" parameterType="java.lang.Long">
select c.*,p.* from category c left join product p on c.cid=p.category_id
<if test="id !=null and id !=''">
where c.cid=#{id}
</if>
</select>
- 測試
@Test
public void testSelectCategoryAndProduct(){
List<Category> categoryList=categoryMapper.selectCategoryAndProduct(null);
categoryList.stream().forEach(i->{
i.getProductList().stream().forEach(product -> System.out.println(product.getProductName()));
});
}
Mybatis方式的一對多查詢就完成了。多對一、多對多查詢這里就不再展示,參照Mybatis即可。
4、 分頁查詢
mp的分頁查詢有兩種方式,BaseMapper分頁和自定義查詢分頁。
4.1、BaseMapper分頁
直接調用方法即可:
@Test
@DisplayName("分頁查詢")
public void testSelectPage(){
QueryWrapper<Product> wrapper = new QueryWrapper<>();
IPage<Product> productIPage=new Page<>(0, 3);
productIPage=productMapper.selectPage(productIPage,wrapper);
System.out.println(productIPage.getRecords().toString());
}
4.2、自定義分頁查詢
- 在前面寫的MybatisPlusConfig.java 配置類sqlSessionFactory方法中添加分頁插件:
//添加分頁插件
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
sqlSessionFactory.setPlugins(new Interceptor[]{paginationInterceptor});
- 定義方法
IPage<Map> selectProductMapWithPage(IPage iPage);
- 查詢腳本
<select id="selectProductMapWithPage" resultType="map">
select p.pid,p.product_name,c.category_name,p.price from product p left join category c on p.category_id=c.cid
</select>
- 測試
@Test
@DisplayName("自定義分頁查詢")
public void testSelectProductMapWithPage(){
Integer pageNo=0;
Integer pageSize=2;
IPage<Map> iPage = new Page<>(pageNo, pageSize);
iPage=productMapper.selectProductMapWithPage(iPage);
iPage.getRecords().stream().forEach(item->{
System.out.println(item.toString());
});
}
- 結果

這里有幾點需要注意:
- 在xml文件里寫的sql語句不要在最后帶上;,因為有些分頁查詢會自動拼上 limit 0, 10; 這樣的sql語句,如果你在定義sql的時候已經加上了 ;,調用這個查詢的時候就會報錯了
- 往xml文件里的查詢方法里傳參數要帶上 @Param("") 注解,這樣mybatis才認,否則會報錯
- 分頁中傳的pageNo可以從0或者1開始,查詢出的結果是一樣的,這一點不像jpa里必須是從0開始才是第一頁
四、代碼生成器
相信用過Mybatis的開發應該都用過Mybatis Gernerator,這種代碼自動生成插件大大減少了我等crud仔的重復工作。MP同樣提供了代碼生成器的功能。
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率。
1、引入依賴
在原來項目的基礎上,添加如下依賴。
- MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關依賴:
<!--代碼生成器依賴-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
- 添加 模板引擎 依賴,MyBatis-Plus 支持 Velocity(默認)、Freemarker、Beetl,用戶可以選擇自己熟悉的模板引擎,如果都不滿足要求,可以采用自定義模板引擎。
Velocity(默認):
<!--模板引擎依賴,即使不需要生成模板,也需要引入-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
- 其它依賴
<!--會生成Controller層,所以引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--代碼生成器中用到了工具類-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
2、代碼生成
下面這個類是代碼生成的一個示例。因為在前后端分離的趨勢下,實際上我們已經很少用模板引擎了,所以這里沒有做模板引擎生成的相關配置。
public class MySQLCodeGenerator {
/**
* <p>
* 讀取控制台內容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
public static void main(String[] args) {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = "D:\\IdeaProjects\\dairly-learn\\springboot-mybatis-plus";
//輸出目錄
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("三分惡");
gc.setOpen(false);
// gc.setSwagger2(true); 實體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
//包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模塊名"));
pc.setParent("cn.fighter3");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
///策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父類實體,沒有就不用設置!");
strategy.setEntityLombokModel(false);
strategy.setRestControllerStyle(true);
// 公共父類
//strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設置!");
// 寫於父類中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.execute();
}
}
- 運行該類,運行結果如下

- 生成的代碼如下:

已經生成了基本的三層結構。在數據庫字段比較多的情況下,還是能減少很多工作量的。
具體更多配置可查看官方文檔 參考【8】。
本文為學習筆記,參考如下!
【1】:MyBatis-Plus簡介
【2】:Spring Boot 2 (十一):如何優雅的使用 MyBatis 之 MyBatis-Plus
【3】:最全的Spring-Boot集成Mybatis-Plus教程
【4】:整合:SpringBoot+Mybatis-plus
【5】:一起來學SpringBoot(十五)MybatisPlus的整合
【6】:整合:SpringBoot+Mybatis-plus
【7】:MyBatis-Plus – 批量插入、更新、刪除、查詢
【8】:MyBatis-Plus 代碼生成器配置
