Mybatis-Plus 详解 拉钩笔记

目录

1. Mybatis-Plus概念

1.1 Mybatis-Plus介绍

1.3 架构

1.4 作者

2. Mybatis-Plus快速⼊⻔

2.1 安装

2.2 创建数据库以及表

2.3 创建⼯程

2.4 Mybatis + MP

2.5 Spring + Mybatis + MP

2.6 SpringBoot + Mybatis + MP

3. 通⽤CRUD

3.1 插⼊操作

3.2 更新操作

3.3 删除操作

3.3.4、deleteBatchIds

3.4 查询操作

3.4.1、selectById

3.4.2、selectBatchIds

3.4.3、selectOne

3.4.4、selectCount

3.4.5、selectList

3.4.6、selectPage

3.5 SQL注⼊的原理

4. 配置

4.1、基本配置

4.1.1、configLocation

4.1.2、mapperLocations

4.1.3、typeAliasesPackage  

4.2、进阶配置

4.2.1、mapUnderscoreToCamelCase

4.2.2、cacheEnabled

4.3、DB 策略配置

4.3.1、idType

4.3.2、tablePrefix

5. 条件构造器

5.1、allEq

5.1.1、说明

5.1.2、测试⽤例

5.2、基本⽐较操作

5.3、模糊查询

5.4、排序

5.6、select

6. ActiveRecord

6.1、开启AR之旅

6.3、新增数据

​编辑 

6.4、更新操作

​编辑

6.5、删除操作

6.6、根据条件查询

7. 插件

7.1、mybatis的插件机制

7.2、执⾏分析插件

7.3、性能分析插件

7.4、乐观锁插件

7.4.1、主要适⽤场景

7.4.2、插件配置

7.4.3、注解实体字段

7.4.4、测试

7.4.5、特别说明

8. Sql 注⼊器

8.1、编写MyBaseMapper

8.2、编写MySqlInjector

8.3、编写FindAll

8.4、注册到Spring容器

8.5、测试

9. ⾃动填充功能

9.1、添加@TableField注解

9.2、编写MyMetaObjectHandler

9.3、测试

10. 逻辑删除

10.1、修改表结构

10.2、配置

10.3、测试

11. 代码⽣成器

11.1、创建⼯程

11.2、代码

11.3、测试

12. MybatisX 快速开发插件


1. Mybatis-Plus概念

1.1 Mybatis-Plus介绍

官⽹: https://mybatis.plus/ https://mp.baomidou.com/
Mybatis-Plus 介绍
MyBatis-Plus (简称 MP )是⼀个 MyBatis 的增强⼯具,在 MyBatis 的基础上只做增强不做改变,-为简化开发、提⾼效率⽽⽣。
Mybatis-Plus 详解 拉钩笔记_第1张图片

愿景
我们的愿景是成为 MyBatis 最好的搭档,就像 魂⽃罗 中的 1P 2P ,基友搭配,效率翻倍。
Mybatis-Plus 详解 拉钩笔记_第2张图片

1.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 查询
  • 分⻚插件⽀持多种数据库:⽀持 MySQLMariaDBOracleDB2H2HSQLSQLitePostgreSQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执⾏时间,建议开发测试时启⽤该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete update 操作智能分析阻断,也可⾃定义拦截规则,预防误操作

1.3 架构

Mybatis-Plus 详解 拉钩笔记_第3张图片

1.4 作者

Mybatis-Plus 是由 baomidou (苞⽶⾖)组织开发并且开源的,⽬前该组织⼤概有 30 ⼈左右。
码云地址: https://gitee.com/organizations/baomidou
Mybatis-Plus 详解 拉钩笔记_第4张图片

2. Mybatis-Plus快速⼊⻔

2.1 安装

全新的 MyBatis-Plus 3.0 版本基于 JDK8 ,提供了 lambda 形式的调⽤,所以安装集成 MP3.0 要求
如下:
  • JDK 8+
  • Maven or Gradle
Release
Spring Boot
Maven

 com.baomidou
 mybatis-plus-boot-starter
 3.4.0
Spring MVC
Maven:

 com.baomidou
 mybatis-plus
 3.4.0
对于 Mybatis 整合 MP 有常常有三种⽤法,分别是 Mybatis+MP Spring+Mybatis+MP Spring
Boot+Mybatis+MP

2.2 创建数据库以及表

Mybatis-Plus 详解 拉钩笔记_第5张图片

创建 User 表,其表结构如下:
Mybatis-Plus 详解 拉钩笔记_第6张图片

-- 创建测试表
DROP TABLE IF EXISTS tb_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)
);
-- 插⼊测试数据
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]');

2.3 创建⼯程

Mybatis-Plus 详解 拉钩笔记_第7张图片

 导⼊依赖:


 
 
 com.baomidou
 mybatis-plus
 3.1.1
 
 
 
 mysql
 mysql-connector-java
 5.1.47
 
 
 
 com.alibaba
 druid
 1.0.11
 
 
 
 org.projectlombok
 lombok
 1.18.4
 
 
 junit
 junit
 4.12
 
 
 org.slf4j
 slf4j-log4j12
 1.6.4
 
 
 
 
 
 org.apache.maven.plugins
 maven-compiler-plugin
 
 1.8
 1.8
 
 
 
 

2.4 Mybatis + MP

下⾯演示,通过纯 Mybatis Mybatis-Plus 整合。
创建⼦ Module


 
 lagou-mybatis-plus
 com.lagou.mp
 1.0-SNAPSHOT
 
 4.0.0

 lagou-mybatis-plus-simple
log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
Mybatis 实现查询 User
第⼀步,编写 mybatis-config.xml ⽂件



 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
第⼆步,编写 User 实体对象:(这⾥使⽤ lombok 进⾏了进化 bean 操作)
@Data // getter setter @toString
@NoArgsConstructor
@AllArgsConstructor
public class User {
 private Long id;
 private String name;
 private Integer age;
 private String email; }
第三步,编写 UserMapper 接⼝:
public interface UserMapper {
 
 List findAll();
}
第四步,编写 UserMapper.xml ⽂件:



 
 
第五步,编写 TestMybatis 测试⽤例:
public class MPTest {
 @Test
 public void test1() throws IOException {
 InputStream resourceAsStream =
Resources.getResourceAsStream("sqlMapConfig.xml");
 SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(resourceAsStream);
 SqlSession sqlSession = sqlSessionFactory.openSession();
 UserMapper mapper = sqlSession.getMapper(UserMapper.class);
 List all = mapper.findAll();
 for (User user : all) {
 System.out.println(user);
 }
 }
}
测试结果:
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
注:如果实体类名称和表名称不⼀致,可以在实体类上添加注解 @TableName(" 指定数据库表名 ")
Mybatis+MP 实现查询 User
第⼀步,将 UserMapper 继承 BaseMapper ,将拥有了 BaseMapper 中的所有⽅法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lagou.pojo.User;
public interface UserMapper extends BaseMapper {
}
第⼆步,使⽤ MP 中的 MybatisSqlSessionFactoryBuilder 进程构建:
@Test
public void test2() throws IOException {
 InputStream resourceAsStream =
Resources.getResourceAsStream("sqlMapConfig.xml");
 //这⾥使⽤的是MP中的MybatisSqlSessionFactoryBuilder
 SqlSessionFactory sqlSessionFactory = new
MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
 SqlSession sqlSession = sqlSessionFactory.openSession();
 UserMapper mapper = sqlSession.getMapper(UserMapper.class);
 // 可以调⽤BaseMapper中定义的⽅法
 List all = mapper.selectList(null);
 for (User user : all) {
 System.out.println(user);
 }
}
测试:
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
注:如果实体类名称和表名称不⼀致,可以在实体类上添加注解 @TableName(" 指定数据库表名 ")
简单说明:
  • 由于使⽤了 MybatisSqlSessionFactoryBuilder进⾏了构建,继承的BaseMapper中的⽅法就载⼊到了SqlSession中,所以就可以直接使⽤相关的⽅法;
  • 如图

Mybatis-Plus 详解 拉钩笔记_第8张图片

2.5 Spring + Mybatis + MP

引⼊了 Spring 框架,数据源、构建等⼯作就交给了 Spring 管理。
创建⼦ Module


 
 lagou-mybatis-plus
 com.lagou.mp
 1.0-SNAPSHOT
 
 4.0.0

 lagou-mybatis-plus-spring
 
 5.1.6.RELEASE
 
 
 
 org.springframework
 spring-webmvc
 ${spring.version}
 
 
 org.springframework
 spring-jdbc
 ${spring.version}
 
 
 org.springframework
 spring-test
 ${spring.version}
 
 
实现查询 User
第⼀步,编写 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=root
第⼆步,编写 applicationContext.xml


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
第三步,编写 User 对象以及 UserMapper 接⼝:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
 private Long id;
 private String name;
 private Integer age;
 private String email; }
public interface UserMapper extends BaseMapper {
 List findAll();
}
第四步,编写测试⽤例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void test2() throws IOException {
 List users = this.userMapper.selectList(null);
 for (User user : users) {
 System.out.println(user);
 }
 }

2.6 SpringBoot + Mybatis + MP

使⽤ SpringBoot 将进⼀步的简化 MP 的整合,需要注意的是,由于使⽤ SpringBoot 需要继承 parent ,所以需要重新创建⼯程,并不是创建⼦Module
创建⼯程
Mybatis-Plus 详解 拉钩笔记_第9张图片

导⼊依赖

 
 org.springframework.boot
 spring-boot-starter
 
 
 org.springframework.boot
 spring-boot-starter-logging
 
 
 
 
 org.springframework.boot
 spring-boot-starter-test
 test
 

 
 
 org.projectlombok
 lombok
 true
 
 
 
 com.baomidou
 mybatis-plus-boot-starter
 3.1.1
 
 
 
 mysql
 mysql-connector-java
 5.1.47
 
 
 org.slf4j
 slf4j-log4j12
 
 
 
 
 
 org.springframework.boot
 spring-boot-maven-plugin
 
 
 
log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

编写application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=tr
ue&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

编写pojo

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
 private Long id;
 private String name;
 private Integer age;
 private String email; 
}
编写 mapper
public interface UserMapper extends BaseMapper {
}
编写启动类
package com.lagou.mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@MapperScan("com.lagou.mp.mapper") //设置mapper接⼝的扫描包
@SpringBootApplication
public class MyApplication {
 public static void main(String[] args) {
 SpringApplication.run(MyApplication.class, args);
 }
}

编写测试⽤例

package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelect() {
 List userList = userMapper.selectList(null);
 for (User user : userList) {
 System.out.println(user);
 }
 }
}
测试:
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])

3. 通⽤CRUD

通过前⾯的学习,我们了解到通过继承 BaseMapper 就可以获取到各种各样的单表操作,接下来我们将详细讲解这些操作。
Mybatis-Plus 详解 拉钩笔记_第10张图片

3.1 插⼊操作

⽅法定义
/**
 * 插⼊⼀条记录
 *
 * @param entity 实体对象.
 */
 int insert(T entity);
测试⽤例
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testInsert(){
 User user = new User();
 user.setAge(18);
 user.setEmail("[email protected]");
 user.setName("⼦慕");
 //返回的result是受影响的⾏数,并不是⾃增后的id
 int result = userMapper.insert(user);
 System.out.println(result);
 System.out.println(user.getId());
 }
}
测试
1
1318744682116739074
Mybatis-Plus 详解 拉钩笔记_第11张图片
可以看到,数据已经写⼊到了数据库,但是, id 的值不正确,我们期望的是数据库⾃增⻓,实际是 MP
成了 id 的值写⼊到了数据库。
如何设置 id 的⽣成策略呢?
MP ⽀持的 id 策略:
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/**
* ⽣成ID类型枚举类
*
* @author hubin
* @since 2015-11-10
*/
@Getter
public enum IdType {
 /**
 * 数据库ID⾃增
 */
 AUTO(0),
 /**
 * 该类型为未设置主键类型
 */
 NONE(1),
 /**
 * ⽤户输⼊ID
 * 

该类型可以通过⾃⼰注册⾃动填充插件进⾏填充

*/ INPUT(2), /* 以下3种类型、只有当插⼊对象ID 为空,才⾃动填充。 */ /** * 全局唯⼀ID (idWorker) */ ID_WORKER(3), /** * 全局唯⼀ID (UUID) */ UUID(4), /** * 字符串全局唯⼀ID (idWorker 的字符串表示) */ ID_WORKER_STR(5); private final int key; IdType(int key) { this.key = key; } }

修改 User 对象:
package com.lagou.mp.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
 @TableId(type = IdType.AUTO) //指定id类型为⾃增⻓
 private Long id;
 private String userName;
 private String password;
 private String name;
 private Integer age;
 private String email;
}
数据插⼊成功:
Mybatis-Plus 详解 拉钩笔记_第12张图片

@TableField
MP 中通过 @TableField 注解可以指定字段的⼀些属性,常常解决的问题有 2 个:
1 、对象中的属性名和字段名不⼀致的问题(⾮驼峰)
2 、对象中的属性字段在表中不存在的问题
使⽤:
Mybatis-Plus 详解 拉钩笔记_第13张图片

 其他⽤法,如⼤字段不加⼊查询字段:

Mybatis-Plus 详解 拉钩笔记_第14张图片

 效果:

Mybatis-Plus 详解 拉钩笔记_第15张图片

3.2 更新操作

MP 中,更新操作有 2 种,⼀种是根据 id 更新,另⼀种是根据条件更新。
根据 id 更新
⽅法定义:
 /**
 * 根据 ID 修改
 *
 * @param entity 实体对象
 */
 int updateById(@Param(Constants.ENTITY) T entity);
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

 @Autowired
 private UserMapper userMapper;
 @Test
 public void testUpdateById() {
 User user = new User();
 user.setId(6L); //主键
 user.setAge(21); //更新的字段
 //根据id更新,更新不为null的字段
 this.userMapper.updateById(user);
 }
}
结果:
Mybatis-Plus 详解 拉钩笔记_第16张图片

根据条件更新
⽅法定义:
/**
 * 根据 whereEntity 条件,更新记录
 *
 * @param entity 实体对象 (set 条件值,可以为 null)
 * @param updateWrapper 实体对象封装操作类(可以为 null,⾥⾯的 entity ⽤于⽣成
where 语句)
 */
 int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER)
Wrapper updateWrapper);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.minidev.json.writer.UpdaterMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testUpdate() {
 User user = new User();
 user.setAge(22); //更新的字段
 //更新的条件
 QueryWrapper wrapper = new QueryWrapper<>();
 wrapper.eq("id", 6);
 //执⾏更新操作
 int result = this.userMapper.update(user, wrapper);
 System.out.println("result = " + result);
 }
}
或者,通过 UpdateWrapper 进⾏更新:
@Test
 public void testUpdate() {
 //更新的条件以及字段
 UpdateWrapper wrapper = new UpdateWrapper<>();
 wrapper.eq("id", 6).set("age", 23);
 //执⾏更新操作
 int result = this.userMapper.update(null, wrapper);
 System.out.println("result = " + result);
 }
测试结果:
[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] == > Preparing: UPDATE
tb_user SET age = ? WHERE id = ?
[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] == > Parameters:
23 (Integer), 6 (Integer)
[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] < == Updates: 1
均可达到更新的效果。
关于 wrapper 更多的⽤法后⾯会详细讲解。

3.3 删除操作

deleteById
⽅法定义:
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testDeleteById() {
 //执⾏删除操作
 int result = this.userMapper.deleteById(6L);
 System.out.println("result = " + result);
 }
}

结果:

[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:
DELETE FROM tb_user WHERE id = ?
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:
6 (Long)
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1
Mybatis-Plus 详解 拉钩笔记_第17张图片
数据被删除。
deleteByMap
⽅法定义:
/**
 * 根据 columnMap 条件,删除记录
 *
 * @param columnMap 表字段 map 对象
 */
 int deleteByMap(@Param(Constants.COLUMN_MAP) Map
columnMap);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testDeleteByMap() {
 Map columnMap = new HashMap<>();
 columnMap.put("age",21);
 columnMap.put("name","⼦慕");
 //将columnMap中的元素设置为删除的条件,多个之间为and关系
 int result = this.userMapper.deleteByMap(columnMap);
 System.out.println("result = " + result);
 }
}

结果:

[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] == > Preparing:
DELETE FROM tb_user WHERE name = ? AND age = ?
[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] == > Parameters:
(String), 21 (Integer)
[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] < == Updates: 0
delete
⽅法定义:
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
结果:
3.3.4、deleteBatchIds
⽅法定义:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testDeleteByMap() {
 User user = new User();
 user.setAge(20);
 user.setName("⼦慕");
 //将实体对象进⾏包装,包装为操作条件
 QueryWrapper wrapper = new QueryWrapper<>(user);
 int result = this.userMapper.delete(wrapper);
 System.out.println("result = " + result);
 }
}

结果:

[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] == > Preparing: DELETE
FROM tb_user WHERE name = ? AND age = ?
[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] == > Parameters: ⼦慕
(String), 20 (Integer)
[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] < == Updates: 0

3.3.4deleteBatchIds

⽅法定义:
/**
 * 删除(根据ID 批量删除)
 *
 * @param idList 主键ID列表(不能为 null 以及 empty)
 */
 int deleteBatchIds(@Param(Constants.COLLECTION) Collection idList);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testDeleteByMap() {
 //根据id集合批量删除
 int result =
this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));
 System.out.println("result = " + result);
 }
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] == > Preparing:
DELETE FROM tb_user WHERE id IN ( ? , ? , ? )
[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] == > Parameters:
1 (Long), 10 (Long), 20 (Long)
[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] < == Updates:
1

3.4 查询操作

MP 提供了多种查询操作,包括根据 id 查询、批量查询、查询单条数据、查询列表、分⻚查询等操作。

3.4.1selectById

⽅法定义:
 /**
 * 根据 ID 查询
 *
 * @param id 主键ID
 */
 T selectById(Serializable id);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectById() {
 //根据id查询数据
 User user = this.userMapper.selectById(2L);
 System.out.println("result = " + user);
 }
}
结果:
result = User (id = 2 , name = Jack, age = 20 , email = [email protected])

3.4.2selectBatchIds

⽅法定义:
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List selectBatchIds(@Param(Constants.COLLECTION) Collection idList);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectBatchIds() {
 //根据id集合批量查询
 List users = this.userMapper.selectBatchIds(Arrays.asList(2L,
3L, 10L));
 for (User user : users) {
 System.out.println(user);
 }
 }
}
结果:
User (id = 2 , name = Jack, age = 20 , email = [email protected])
User (id = 3 , name = Tom, age = 28 , email = [email protected])

3.4.3selectOne

⽅法定义:
/**
* 根据 entity 条件,查询⼀条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectOne() {
 QueryWrapper wrapper = new QueryWrapper();
 wrapper.eq("name", "jack");
 //根据条件查询⼀条数据,如果结果超过⼀条会报错
 User user = this.userMapper.selectOne(wrapper);
 System.out.println(user);
 }
}
结果:
User (id = 2 , name = Jack, age = 20 , email = [email protected])

3.4.4selectCount

⽅法定义:
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectCount() {
 QueryWrapper wrapper = new QueryWrapper();
 wrapper.gt("age", 23); //年龄⼤于23岁
 //根据条件查询数据条数
 Integer count = this.userMapper.selectCount(wrapper);
 System.out.println("count = " + count);
 }
}
结果:
count = 2

3.4.5selectList

⽅法定义:
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectList() {
 QueryWrapper wrapper = new QueryWrapper();
 wrapper.gt("age", 23); //年龄⼤于23岁
 //根据条件查询数据
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println("user = " + user);
 }
 }
}
结果:
user = User (id = 3 , name = Tom, age = 28 , email = [email protected])
user = User (id = 5 , name = Billie, age = 24 , email = [email protected])

3.4.6selectPage

⽅法定义:
/**
* 根据 entity 条件,查询全部记录(并翻⻚)
*
* @param page 分⻚查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper
queryWrapper);
配置分⻚插件:
package com.lagou.mp;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.lagou.mp.mapper") //设置mapper接⼝的扫描包
public class MybatisPlusConfig {
 /**
 * 分⻚插件
 */
 @Bean
 public PaginationInterceptor paginationInterceptor() {
 return new PaginationInterceptor();
 }
}
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectPage() {
 QueryWrapper wrapper = new QueryWrapper();
 wrapper.gt("age", 20); //年龄⼤于20岁
 Page page = new Page<>(1,1);
 //根据条件查询数据
 IPage iPage = this.userMapper.selectPage(page, wrapper);
 System.out.println("数据总条数:" + iPage.getTotal());
 System.out.println("总⻚数:" + iPage.getPages());
 List users = iPage.getRecords();
 for (User user : users) {
 System.out.println("user = " + user);
 }
 }
}

结果:

数据总条数: 4
总⻚数: 4
user = User (id = 3 , name = Tom, age = 28 , email = [email protected])

3.5 SQL注⼊的原理

前⾯我们已经知道, MP 在启动后会将 BaseMapper 中的⼀系列的⽅法注册到 meppedStatements 中, 那么究竟是如何注⼊的呢?流程⼜是怎么样的?下⾯我们将⼀起来分析下。
MP 中, ISqlInjector 负责 SQL 的注⼊⼯作,它是⼀个接⼝, AbstractSqlInjector 是它的实现类,实现关系如下:
Mybatis-Plus 详解 拉钩笔记_第18张图片

AbstractSqlInjector 中,主要是由 inspectInject() ⽅法进⾏注⼊的,如下:
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class
mapperClass) {
 Class modelClass = extractModelClass(mapperClass);
 if (modelClass != null) {
 String className = mapperClass.toString();
 Set mapperRegistryCache =
GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
 if (!mapperRegistryCache.contains(className)) {
 List methodList = this.getMethodList();
 if (CollectionUtils.isNotEmpty(methodList)) {
 TableInfo tableInfo =
TableInfoHelper.initTableInfo(builderAssistant, modelClass);
 // 循环注⼊⾃定义⽅法
 methodList.forEach(m -> m.inject(builderAssistant,
mapperClass, modelClass, tableInfo));
 } else {
 logger.debug(mapperClass.toString() + ", No effective
injection method was found.");
 }
 mapperRegistryCache.add(className);
 }
 }
}
在实现⽅法中, methodList.forEach(m -> m.inject(builderAssistant, mapperClass,
modelClass, tableInfo)); 是关键,循环遍历⽅法,进⾏注⼊。
最终调⽤抽象⽅法 injectMappedStatement 进⾏真正的注⼊:
/**
 * 注⼊⾃定义 MappedStatement
 *
 * @param mapperClass mapper 接⼝
 * @param modelClass mapper 泛型
 * @param tableInfo 数据库表反射信息
 * @return MappedStatement
 */
 public abstract MappedStatement injectMappedStatement(Class
mapperClass, Class modelClass, TableInfo tableInfo);
查看该⽅法的实现:
Mybatis-Plus 详解 拉钩笔记_第19张图片

SelectById 为例查看:
public class SelectById extends AbstractMethod {
 @Override
 public MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) {
 SqlMethod sqlMethod = SqlMethod.LOGIC_SELECT_BY_ID;
 SqlSource sqlSource = new RawSqlSource(configuration,
String.format(sqlMethod.getSql(),
 sqlSelectColumns(tableInfo, false),
 tableInfo.getTableName(), tableInfo.getKeyColumn(),
tableInfo.getKeyProperty(),
 tableInfo.getLogicDeleteSql(true, false)), Object.class);
 return this.addSelectMappedStatement(mapperClass,
sqlMethod.getMethod(), sqlSource, modelClass, tableInfo);
 }
}
可以看到,⽣成了 SqlSource 对象,再将 SQL 通过 addSelectMappedStatement ⽅法添加到meppedStatements中。
Mybatis-Plus 详解 拉钩笔记_第20张图片

4. 配置

MP 中有⼤量的配置,其中有⼀部分是 Mybatis 原⽣的配置,另⼀部分是 MP 的配置,详情: https://m
ybatis.plus/config/
下⾯我们对常⽤的配置做讲解。

4.1、基本配置

4.1.1configLocation

MyBatis 配置⽂件位置,如果有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。
MyBatis Configuration 的具体内容请参考 MyBatis 官⽅⽂档
Spring Boot
mybatis-plus.config-location = classpath:mybatis-config.xml

Spring MVC


 

4.1.2mapperLocations

MyBatis Mapper 所对应的 XML ⽂件位置,如果您在 Mapper 中有⾃定义⽅法( XML 中有⾃定义实现),需要进⾏该配置,告诉 Mapper 所对应的 XML ⽂件位置。
Spring Boot
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
Spring MVC

 
Maven 多模块项⽬的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML ⽂件)
测试:
UserMapper.xml



 
package com.lagou.mp.mapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper {
 User findById(Long id);
}
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testSelectPage() {
 User user = this.userMapper.findById(2L);
 System.out.println(user);
 }
}
运⾏结果:
Mybatis-Plus 详解 拉钩笔记_第21张图片

4.1.3typeAliasesPackage  

MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML ⽂件中可以直接使⽤类名,⽽不⽤使⽤全限定的类名(即 XML 中调⽤的时候不⽤包含包名)。
Spring Boot
mybatis-plus.type-aliases-package = com.lagou.mp.pojo
Spring MVC

 

4.2、进阶配置

本部分( Configuration )的配置⼤都为 MyBatis 原⽣⽀持的配置,这意味着您可以通过 MyBatis XML配置⽂件的形式进⾏配置。

4.2.1mapUnderscoreToCamelCase

  • 类型: boolean
  • 默认值: true
是否开启⾃动驼峰命名规则( camel case )映射,即从经典数据库列名 A_COLUMN (下划线命名) 到经典 Java 属性名 aColumn (驼峰命名) 的类似映射。
注意:
此属性在 MyBatis 中原默认值为 false ,在 MyBatis-Plus 中,此属性也将⽤于⽣成最终的 SQL 的select body
如果您的数据库命名符合规则⽆需使⽤ @TableField 注解指定数据库字段名
示例( SpringBoot ):
 
#关闭⾃动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false

4.2.2cacheEnabled

  • 类型: boolean
  • 默认值: true
全局地开启或关闭配置⽂件中的所有映射器已经配置的任何缓存,默认为 true
示例:
mybatis-plus.configuration.cache-enabled=false

4.3DB 策略配置

4.3.1idType

  • 类型: com.baomidou.mybatisplus.annotation.IdType
  • 默认值: ID_WORKER
全局默认主键类型,设置后,即可省略实体对象中的 @TableId(type = IdType.AUTO) 配置。
示例:
SpringBoot
mybatis-plus.global-config.db-config.id-type=auto
SpringMVC

 
 
 
 
 
 
 
 
 
 
 
 

4.3.2tablePrefix

  • 类型: String
  • 默认值: null
表名前缀,全局配置后可省略 @TableName() 配置。
SpringBoot
mybatis-plus.global-config.db-config.table-prefix=tb_
SpringMVC

 
 
 
 
 
 
 
 
 
 
 
 

5. 条件构造器

MP 中, Wrapper 接⼝的实现类关系如下:
Mybatis-Plus 详解 拉钩笔记_第22张图片

可以看到, AbstractWrapper AbstractChainWrapper 是重点实现,接下来我们重点学习
AbstractWrapper 以及其⼦类。
说明 :
QueryWrapper(LambdaQueryWrapper) UpdateWrapper(LambdaUpdateWrapper) 的⽗类
⽤于⽣成 sql where 条件 , entity 属性也⽤于⽣成 sql where 条件
注意 : entity ⽣成的 where 条件与 使⽤各个 api ⽣成的 where 条件 没有任何关联⾏为
官⽹⽂档地址: https://mybatis.plus/guide/wrapper.html

5.1allEq

5.1.1、说明

allEq(Map params)
allEq(Map params, boolean null2IsNull)
allEq(boolean condition, Map 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 filter, Map params)
allEq(BiPredicate filter, Map params, boolean null2IsNull)
allEq(boolean condition, BiPredicate filter, Map 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 = ' ⽼王 '

5.1.2、测试⽤例

package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testWrapper() {
 QueryWrapper wrapper = new QueryWrapper<>();
 //设置条件
 Map params = new HashMap<>();
 params.put("name", "jack");
 params.put("age", "20");
// wrapper.allEq(params);//SELECT * FROM tb_user WHERE password IS NULL
AND name = ? AND age = ?
// wrapper.allEq(params,false); //SELECT * FROM tb_user WHERE name = ?
AND age = ?
// wrapper.allEq((k, v) -> (k.equals("name") || k.equals("age"))
,params);//SELECT * FROM tb_user WHERE name = ? AND age = ?
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

5.2、基本⽐较操作

  • eq
    • 等于 =
  • ne
    • 不等于 <>
  • gt
    • ⼤于 >
  • ge
    • ⼤于等于 >=
  • lt
    • ⼩于 <
  • le
    • ⼩于等于 <=
  • between
    • BETWEEN 1 AND 2
  • notBetween
    • NOT BETWEEN 1 AND 2
  • in
    • 字段 IN (value.get(0), value.get(1), ...)
  • notIn
    • 字段 NOT IN (v0, v1, ...)
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 QueryWrapper wrapper = new QueryWrapper<>();
 //SELECT id,name,age,email FROM tb_user WHERE password = ? AND age >=
? AND name IN (?,?,?)
 wrapper.eq("email", "[email protected]")
 .ge("age", 20)
 .in("name", "jack", "jone", "tom");
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

5.3、模糊查询

  • like
    • LIKE '%值%'
    • 例: like("name", "") ---> name like '%%'
  • notLike
    • NOT LIKE '%%'
    • : notLike("name", "") ---> name not like '%%'
  • likeLeft
    • LIKE '%'
    • : likeLeft("name", "") ---> name like '%'
  • likeRight
    • LIKE '%'
    • : likeRight("name", "") ---> name like '%'
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testWrapper() {
 QueryWrapper wrapper = new QueryWrapper<>();
 //SELECT id,user_name,password,name,age,email FROM tb_user WHERE name
LIKE ?
 //Parameters: %⼦%(String)
 wrapper.like("name", "⼦");
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

5.4、排序

  • orderBy
    • 排序:ORDER BY 字段, ...
    • : orderBy(true, true, "id", "name") ---> order by id ASC,name ASC
  • orderByAsc
    • 排序:ORDER BY 字段, ... ASC
    • : orderByAsc("id", "name") ---> order by id ASC,name ASC
  • orderByDesc
    • 排序:ORDER BY 字段, ... DESC
    • : orderByDesc("id", "name") ---> order by id DESC,name DESC
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testWrapper() {
 QueryWrapper wrapper = new QueryWrapper<>();
 //SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY
age DESC
 wrapper.orderByDesc("age");
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

5.5、逻辑查询

  • or
    • 拼接 OR
    • 主动调⽤ or 表示紧接着下⼀个⽅法不是⽤ and 连接!(不调⽤ or 则默认为使⽤ and 连接)
  • and
    • AND 嵌套
    • : and(i -> i.eq("name", "李⽩").ne("status", "活着")) ---> and (name = '' and status <> '活着')
测试⽤例:
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testWrapper() {
 QueryWrapper wrapper = new QueryWrapper<>();

 //SELECT id,user_name,password,name,age,email FROM tb_user WHERE name= ? OR age = ?
 wrapper.eq("name","jack").or().eq("age", 24);
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

5.6select

MP 查询中,默认查询所有的字段,如果有需要也可以通过 select ⽅法进⾏指定字段。
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testWrapper() {
 QueryWrapper wrapper = new QueryWrapper<>();
 //SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
 wrapper.eq("name", "jack")
 .or()
 .eq("age", 24)
 .select("id", "name", "age");
 List users = this.userMapper.selectList(wrapper);
 for (User user : users) {
 System.out.println(user);
 }
 }
}

6. ActiveRecord

ActiveRecord (简称 AR )⼀直⼴受动态语⾔( PHP Ruby 等)的喜爱,⽽ Java 作为准静态语⾔,对于 ActiveRecord 往往只能感叹其优雅,所以我们也在 AR 道路上进⾏了⼀定的探索,希望⼤家能够喜欢。 
什么是 ActiveRecord
ActiveRecord 也属于 ORM (对象关系映射)层,由 Rails 最早提出,遵循标准的 ORM 模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很⼤程度的快速实现模型的操作,⽽且简洁易懂。
ActiveRecord 的主要思想是:
  • 每⼀个数据库表对应创建⼀个类,类的每⼀个对象实例对应于数据库中表的⼀⾏记录;通常 表的每个字段在类中都有相应的Field
  • ActiveRecord同时负责把⾃⼰持久化,在ActiveRecord中封装了对数据库的访问,即 CURD;
  • ActiveRecord是⼀种领域模型(Domain Model),封装了部分业务逻辑;

6.1、开启AR之旅

MP 中,开启 AR ⾮常简单,只需要将实体对象继承 Model 即可。
package com.lagou.mp.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User extends Model {

 private Long id;
 private String userName;
 private String password;
 private String name;
 private Integer age;
 private String email; 
}

6.2、根据主键查询

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testAR() {
 User user = new User();
 user.setId(2L);
 User user2 = user.selectById();
 System.out.println(user2);
 }
}

6.3、新增数据

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testARInsert() {
 User user = new User();
 user.setName("应颠");
 user.setAge(30);
 user.setEmail("[email protected]");
 boolean insert = user.insert();
 System.out.println(insert);
 }
}
[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] == > Preparing: INSERT
INTO tb_user ( name, age, email ) VALUES ( ?, ?, ?, ?, ? )
[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] == > Parameters: 应癫
(String), 30 (Integer), [email protected](String)
[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] < == Updates: 1

Mybatis-Plus 详解 拉钩笔记_第23张图片

6.4、更新操作

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testAR() {
 User user = new User();
 user.setId(8L);
 user.setAge(35);
 boolean update = user.updateById();
 System.out.println(update);
 }
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Preparing:
UPDATE tb_user SET age = ? WHERE id = ?
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Parameters:
35 (Integer), 8 (Long)
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] < == Updates: 1

Mybatis-Plus 详解 拉钩笔记_第24张图片

6.5、删除操作

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testAR() {
 User user = new User();
 user.setId(7L);
 boolean delete = user.deleteById();
 System.out.println(delete);
 }
}

结果:

[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:
DELETE FROM tb_user WHERE id = ?
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:
7 (Long)
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1

6.6、根据条件查询

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
 @Autowired
 private UserMapper userMapper;
 @Test
 public void testARFindById() {
 User user = new User();
 QueryWrapper userQueryWrapper = new QueryWrapper<>();
 userQueryWrapper.le("age","20");
 List users = user.selectList(userQueryWrapper);
 for (User user1 : users) {
 System.out.println(user1);
 }
 }
}
结果:
User (id = 1 , name = Jone, age = 18 , email = [email protected])
User (id = 2 , name = Jack, age = 20 , email = [email protected])
User (id = 7 , name = ⼦慕 , age = 18 , email = [email protected])

7. 插件

7.1mybatis的插件机制

MyBatis 允许你在已映射语句执⾏过程中的某⼀点进⾏拦截调⽤。默认情况下, MyBatis 允许使⽤插件
来拦截的⽅法调⽤包括:
1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
2. ParameterHandler (getParameterObject, setParameters)
3. ResultSetHandler (handleResultSets, handleOutputParameters)
4. StatementHandler (prepare, parameterize, batch, update, query)
我们看到了可以拦截 Executor 接⼝的部分⽅法,⽐如 update query commit rollback 等⽅法,还有其他接⼝的⼀些⽅法等。
总体概括为:
1. 拦截执⾏器的⽅法
2. 拦截参数的处理
3. 拦截结果集的处理
4. 拦截 Sql 语法构建的处理
拦截器示例:
package com.lagou.mp.plugins;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
@Intercepts({@Signature(
 type= Executor.class,
 method = "update",
 args = {MappedStatement.class,Object.class})})
public class MyInterceptor implements Interceptor {
 @Override
 public Object intercept(Invocation invocation) throws Throwable {
 //拦截⽅法,具体业务逻辑编写的位置
 return invocation.proceed();
 }
 @Override
 public Object plugin(Object target) {
 //创建target对象的代理对象,⽬的是将当前拦截器加⼊到该对象中
 return Plugin.wrap(target, this);
 }
 @Override
 public void setProperties(Properties properties) {
 //属性设置
 }
}

注⼊到Spring容器:

/**
 * ⾃定义拦截器
 */
 @Bean
 public MyInterceptor myInterceptor(){
 return new MyInterceptor();
 }

或者通过xml配置,mybatis-config.xml




 
 
 

7.2、执⾏分析插件

MP 中提供了对 SQL 执⾏的分析的插件,可⽤作阻断全表更新、删除的操作,注意:该插件仅适⽤于开发环境,不适⽤于⽣产环境。
SpringBoot 配置:
@Bean
public SqlExplainInterceptor sqlExplainInterceptor(){
 SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
 List sqlParserList = new ArrayList<>();
 // 攻击 SQL 阻断解析器、加⼊解析链
 sqlParserList.add(new BlockAttackSqlParser());
 sqlExplainInterceptor.setSqlParserList(sqlParserList);
 return sqlExplainInterceptor; }
测试:
@Test
public void testUpdate(){
 User user = new User();
 user.setAge(20);
 int result = this.userMapper.update(user, null);
 System.out.println("result = " + result);
}
结果:
Caused by: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException:
Prohibition of table update operation
at
com.baomidou.mybatisplus.core.toolkit.ExceptionUtils.mpe(ExceptionUtils.java:4
9)
at com.baomidou.mybatisplus.core.toolkit.Assert.isTrue(Assert.java:38)
at com.baomidou.mybatisplus.core.toolkit.Assert.notNull(Assert.java:72)
at
com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser.processUpdate(
BlockAttackSqlParser.java:45)
at
com.baomidou.mybatisplus.core.parser.AbstractJsqlParser.processParser(Abstract
JsqlParser.java:92)
at
com.baomidou.mybatisplus.core.parser.AbstractJsqlParser.parser(AbstractJsqlPar
ser.java:67)
at
com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler.sqlParser
(AbstractSqlParserHandler.java:76)
at
com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor.intercept(Sql
ExplainInterceptor.java:63)
at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
at com.sun.proxy. $Proxy70 .update(Unknown Source)
at
org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.
java:197)
... 41 more
可以看到,当执⾏全表更新时,会抛出异常,这样有效防⽌了⼀些误操作。

7.3、性能分析插件

性能分析拦截器,⽤于输出每条 SQL 语句及其执⾏时间,可以设置最⼤执⾏时间,超过时间会抛出异常。
该插件只⽤于开发环境,不建议⽣产环境使⽤。
配置:
javaconfig ⽅式
@Bean
public PerformanceInterceptor performanceInterceptor(){
 PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
 performanceInterceptor.setMaxTime(100);
 performanceInterceptor.setFormat(true);
 return performanceInterceptor; }
xml ⽅式



 
 
 
 
 
 
 
 
执⾏结果:
Time 11 ms - ID com.lagou.mp.mapper.UserMapper.selectById
Execute SQL
SELECT
id,
user_name,
password,
name,
age,
email
FROM
tb_user
WHERE
id = 7
可以看到,执⾏时间为 11ms 。如果将 maxTime 设置为 1 ,那么,该操作会抛出异常。

7.4、乐观锁插件

7.4.1、主要适⽤场景

意图:
当要更新⼀条记录的时候,希望这条记录没有被别⼈更新
乐观锁实现⽅式:
  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执⾏更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

7.4.2、插件配置

spring xml:
spring boot:
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
 return new OptimisticLockerInterceptor();
}

7.4.3、注解实体字段

需要为实体字段添加 @Version 注解。
第⼀步,为表添加 version 字段,并且设置初始值为 1
ALTER TABLE `tb_user`
ADD COLUMN `version` int(10) NULL AFTER `email`;
UPDATE `tb_user` SET `version`='1';

第⼆步,为User实体对象添加version字段,并且添加@Version注解:

@Version
private Integer version;

7.4.4、测试

测试⽤例:
@Test
public void testUpdate(){
 User user = new User();
 user.setAge(30);
 user.setId(2L);
 user.setVersion(1); //获取到version为1
 int result = this.userMapper.updateById(user);
 System.out.println("result = " + result);
}
执⾏⽇志:
main] [com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser]-
[DEBUG] Original SQL: UPDATE tb_user SET age = ?,
version = ? WHERE id = ? AND version = ?
[main] [com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser]-
[DEBUG] parser sql: UPDATE tb_user SET age = ?, version = ? WHERE id = ? AND
version = ?
[main] [org.springframework.jdbc.datasource.DataSourceUtils]-[DEBUG] Fetching
JDBC Connection from DataSource
[main] [org.mybatis.spring.transaction.SpringManagedTransaction]-[DEBUG] JDBC
Connection [HikariProxyConnection@540206885 wrapping
com.mysql.jdbc.JDBC4Connection@27e0f2f5] will not be managed by Spring
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Preparing:
UPDATE tb_user SET age = ?, version = ? WHERE id = ? AND version = ?
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Parameters:
30 (Integer), 2 (Integer), 2 (Long), 1 (Integer)
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] < == Updates: 1
[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactional
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@30135202]
result = 1
可以看到,更新的条件中有 version 条件,并且更新的 version 2
如果再次执⾏,更新则不成功。这样就避免了多⼈同时更新时导致数据的不⼀致。

7.4.5、特别说明

  • ⽀持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
  • 整数类型下 newVersion = oldVersion + 1
  • newVersion 会回写到 entity
  • 仅⽀持 updateById(id) update(entity, wrapper) ⽅法
  • update(entity, wrapper) ⽅法下, wrapper 不能复⽤!!!

8. Sql 注⼊器

我们已经知道,在 MP 中,通过 AbstractSqlInjector BaseMapper 中的⽅法注⼊到了 Mybatis 容器,这样这些⽅法才可以正常执⾏。
那么,如果我们需要扩充 BaseMapper 中的⽅法,⼜该如何实现呢?
下⾯我们以扩展 findAll ⽅法为例进⾏学习。

8.1、编写MyBaseMapper

package com.lagou.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
public interface MyBaseMapper extends BaseMapper {
 List findAll();
}
其他的 Mapper 都可以继承该 Mapper ,这样实现了统⼀的扩展。
如:
package com.lagou.mp.mapper;
import com.lagou.mp.pojo.User;
public interface UserMapper extends MyBaseMapper {
 User findById(Long id);
}

8.2、编写MySqlInjector

如果直接继承 AbstractSqlInjector 的话,原有的 BaseMapper 中的⽅法将失效,所以我们选择继承
DefaultSqlInjector 进⾏扩展。
package com.lagou.mp.sqlInjector;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import java.util.List;
public class MySqlInjector extends DefaultSqlInjector {
 @Override
 public List getMethodList() {
 List methodList = super.getMethodList();
 methodList.add(new FindAll());
 
 // 再扩充⾃定义的⽅法
 list.add(new FindAll());
 return methodList;
 }
}

8.3、编写FindAll

package com.lagou.mp.sqlInjector;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
public class FindAll extends AbstractMethod {
 @Override
 public MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) {
 String sqlMethod = "findAll";
 String sql = "select * from " + tableInfo.getTableName();
 SqlSource sqlSource = languageDriver.createSqlSource(configuration,
sql, modelClass);
 return this.addSelectMappedStatement(mapperClass, sqlMethod,
sqlSource, modelClass, tableInfo);
 }
}

8.4、注册到Spring容器

/**
* ⾃定义SQL注⼊器
*/
@Bean
public MySqlInjector mySqlInjector(){
 return new MySqlInjector();
}

8.5、测试

@Test
public void testFindAll(){
 List users = this.userMapper.findAll();
 for (User user : users) {
 System.out.println(user);
 }
}
输出的 SQL
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] == > Preparing: select
* from tb_user
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] == > Parameters:
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] < == Total: 10
⾄此,我们实现了全局扩展 SQL 注⼊器。

9. ⾃动填充功能

有些时候我们可能会有这样的需求,插⼊或者更新数据时,希望有些字段可以⾃动填充数据,⽐如密码、version 等。在 MP 中提供了这样的功能,可以实现⾃动填充。

9.1、添加@TableField注解

@TableField(fill = FieldFill.INSERT) //插⼊数据时进⾏填充
private String version;
email 添加⾃动填充功能,在新增数据时有效。
FieldFill 提供了多种模式选择:
public enum FieldFill {
9.2、编写MyMetaObjectHandler
9.3、测试
 /**
 * 默认不处理
 */
 DEFAULT,
 /**
 * 插⼊时填充字段
 */
 INSERT,
 /**
 * 更新时填充字段
 */
 UPDATE,
 /**
 * 插⼊和更新时填充字段
 */
 INSERT_UPDATE
}

9.2、编写MyMetaObjectHandler

package com.lagou.mp.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
 @Override
 public void insertFill(MetaObject metaObject) {
 Object password = getFieldValByName("version", metaObject);
 if(null == password){
 //字段为空,可以进⾏填充
 setFieldValByName("version", "123456", metaObject);
 }
 }
 @Override
 public void updateFill(MetaObject metaObject) {
 }
}

9.3、测试

@Test
public void testInsert(){
 User user = new User();
 user.setName("冰冰");
 user.setAge(30);
 user.setVersion(1);
 int result = this.userMapper.insert(user);
 System.out.println("result = " + result);
}
结果:
Mybatis-Plus 详解 拉钩笔记_第25张图片

10. 逻辑删除

开发系统时,有时候在实现功能时,删除操作需要实现逻辑删除,所谓逻辑删除就是将数据标记为删除,⽽并⾮真正的物理删除(⾮DELETE 操作),查询时需要携带状态条件,确保被标记的数据不被查询到。这样做的⽬的就是避免数据被真正的删除。
MP 就提供了这样的功能,⽅便我们使⽤,接下来我们⼀起学习下。

10.1、修改表结构

ALTER TABLE `tb_user`
ADD COLUMN `deleted` int(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除'
AFTER `version`;
tb_user 表增加 deleted 字段,⽤于表示数据是否被删除, 1 代表删除, 0 代表未删除。
同时,也修改 User 实体,增加 deleted 属性并且添加 @TableLogic 注解:
@TableLogic
private Integer deleted;

10.2、配置

application.properties
# 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0

10.3、测试

@Test
public void testDeleteById(){
 this.userMapper.deleteById(2L);
}
执⾏的 SQL
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:
UPDATE tb_user SET deleted = 1 WHERE id = ? AND deleted = 0
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:
2 (Long)
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1
Mybatis-Plus 详解 拉钩笔记_第26张图片

测试查询:
@Test
public void testSelectById(){
 User user = this.userMapper.selectById(2L);
 System.out.println(user);
}
执⾏的 SQL
[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] == > Preparing:
SELECT id,user_name,password,name,age,email,version,deleted FROM tb_user WHERE
id = ? AND deleted = 0
[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] == > Parameters:
2 (Long)
[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] < == Total: 0
可⻅,已经实现了逻辑删除。

11. 代码⽣成器

AutoGenerator MyBatis-Plus 的代码⽣成器,通过 AutoGenerator 可以快速⽣成 Entity
Mapper Mapper XML Service Controller 等各个模块的代码,极⼤的提升了开发效率。

11.1、创建⼯程

pom.xml


 4.0.0
 
 org.springframework.boot
 spring-boot-starter-parent
 2.3.4.RELEASE
  
 
 com.lagou
 lagou-mp-generator
 0.0.1-SNAPSHOT
 lagou-mp-generator
 Demo project for Spring Boot
 
 11
 
 
 
 org.springframework.boot
 spring-boot-starter-test
 test
 
 
 
 com.baomidou
 mybatis-plus-boot-starter
 3.1.1
 
 
 com.baomidou
 mybatis-plus-generator
 3.1.1
 
 
 org.springframework.boot
 spring-boot-starter-freemarker
 
 
 
 mysql
 mysql-connector-java
 5.1.47
 
 
 org.slf4j
 slf4j-log4j12
 
 
 org.springframework.boot
 spring-boot-starter-web
 
 
 
 org.projectlombok
 lombok
 true
 
 
 
 
 
 org.springframework.boot
 spring-boot-maven-plugin
 
 
 

11.2、代码

package com.lagou.mp.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
* 

* mysql 代码⽣成器演示例⼦ *

*/ public class MysqlGenerator { /** *

* 读取控制台内容 *

*/ 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.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输⼊正确的" + tip + "!"); } /** * RUN THIS */ public static void main(String[] args) { // 代码⽣成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("lagou"); gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mp? useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模块名")); pc.setParent("com.lagou.mp.generator"); mpg.setPackageInfo(pc); // ⾃定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // ⾃定义输⼊⽂件名称 return projectPath + "/lagou-mpgenerator/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity"); strategy.setEntityLombokModel(true); //strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController"); strategy.setInclude(scanner("表名")); strategy.setSuperEntityColumns("id"); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有! mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

11.3、测试

Mybatis-Plus 详解 拉钩笔记_第27张图片

代码已⽣成:
Mybatis-Plus 详解 拉钩笔记_第28张图片

实体对象:
Mybatis-Plus 详解 拉钩笔记_第29张图片

12. MybatisX 快速开发插件

MybatisX 是⼀款基于 IDEA 的快速开发插件,为效率⽽⽣。
安装⽅法:打开 IDEA ,进⼊ File -> Settings -> Plugins -> Browse Repositories ,输⼊ mybatisx 搜索并安装。
功能:
  • Java XML 调回跳转
  • Mapper ⽅法⾃动⽣成 XML

Mybatis-Plus 详解 拉钩笔记_第30张图片

 Mybatis-Plus 详解 拉钩笔记_第31张图片

 Mybatis-Plus 详解 拉钩笔记_第32张图片

你可能感兴趣的:(#,持久层框架,mybatis,spring,java)