Mybatis-Plus01

课程介绍

  • 了解Mybatis-Plus
  • 整合Mybatis-Plus
  • 通用CRUD
  • Mybatis-Plus的配置
  • 条件构造器

文章目录

  • Mybatis-Plus01
    • 课程介绍
    • 1、了解Mybatis-Plus
      • 1.1、Mybatis-Plus介绍
      • 1.2、代码以及文档
      • 1.3、特性
      • 1.4、架构
      • 1.5、作者
    • 2、快速开始
      • 2.1、创建数据库以及表
      • 2.2、创建工程
      • 2.3、Mybatis + MP
        • 2.3.1、创建子Module
        • 2.3.2、Mybatis实现查询User
        • 2.3.3、Mybatis+MP实现查询User
      • 2.4、Spring + Mybatis + MP
        • 2.4.1、创建子Module
        • 2.4.2、实现查询User
      • 2.5、SpringBoot + Mybatis + MP
        • 2.5.1、创建工程
        • 2.5.2、导入依赖
        • 2.5.3、编写application.properties
        • 2.5.4、编写pojo
        • 2.5.5、编写mapper
        • 2.5.6、编写启动类
        • 2.5.7、编写测试用例
    • 3、通用CRUD
      • 3.1、插入操作
        • 3.1.1、测试用例
        • 3.1.2、执行测试结果
        • 3.1.3、ID生成策略
        • 3.1.4、@TableField
      • 3.2、更新操作
        • 3.2.1、根据id更新
        • 3.2.2、根据条件更新
      • 3.3、删除操作
        • 3.3.1、deleteById
        • 3.3.2、deleteByMap
        • 3.3.3、delete
        • 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
    • 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.5、逻辑查询
      • 5.6、select
      • 5.6、select

1、了解Mybatis-Plus

1.1、Mybatis-Plus介绍

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网:https://mybatis.plus/ 或 https://mp.baomidou.com/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vBGthtfy-1672022032488)(Pictures/1556243079102.png)]

愿景

我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2cH5K6kP-1672022032488)(Pictures/relationship-with-mybatis.png)]

1.2、代码以及文档

文档地址:https://mybatis.plus/guide/

源码地址:https://github.com/baomidou/mybatis-plus

1.3、特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持关键词自动转义:支持数据库关键词(order、key…)自动转义,还可自定义关键词
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
  • 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

1.4、架构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3H01Kfe2-1672022032488)(Pictures/mybatis-plus-framework.jpg)]

1.5、作者

Mybatis-Plus是由baomidou(苞米豆)组织开发并且开源的,目前该组织大概有30人左右。

码云地址:https://gitee.com/organizations/baomidou

2、快速开始

对于Mybatis整合MP有常常有三种用法,分别是Mybatis+MP、Spring+Mybatis+MP、Spring Boot+Mybatis+MP。

2.1、创建数据库以及表

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HhSmm9Ry-1672022032489)(Pictures\01.png)]

-- 创建测试表
CREATE TABLE `tb_user` (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',`user_name` varchar(20) NOT NULL COMMENT '用户名',`password` varchar(20) NOT NULL COMMENT '密码',`name` varchar(30) DEFAULT NULL COMMENT '姓名',`age` int(11) DEFAULT NULL COMMENT '年龄',`email` varchar(50) DEFAULT NULL COMMENT '邮箱',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;-- 插入测试数据
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('1', 'qinglong', '123456', '青龙', '18', 'test1@1000phone.com');
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('2', 'baihu', '123456', '白虎', '20', 'test2@1000phone.com');
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('3', 'zhuque', '123456', '朱雀', '28', 'test3@1000phone.com');
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('4', 'xuanwu', '123456', '玄武', '21', 'test4@1000phone.com');
INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES ('5', 'taoti', '123456', '饕鬄', '24', 'test5@1000phone.com');

2.2、创建工程

新建Model, Maven项目, 不要选择Maven骨架.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HdIVJoUk-1672022032489)(Pictures\02.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RjnPKbUM-1672022032490)(Pictures\03.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ks6U5HYO-1672022032490)(Pictures\04.png)]

项目Pom.xml中导入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.qianfeng</groupId><artifactId>qianfeng_mybatis_plus</artifactId><version>1.0-SNAPSHOT</version><packaging>pom</packaging><properties><!-- 项目源码及编译输出的编码 --><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><!-- 项目编译JDK版本 --><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><!-- mybatis-plus插件依赖 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.1.1</version></dependency><!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!-- 连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.11</version></dependency><!--简化bean代码的工具包--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional><version>1.18.4</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.6.4</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build></project>

2.3、Mybatis + MP

下面演示,通过纯Mybatis与Mybatis-Plus整合。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1kukF3aL-1672022032490)(Pictures\05.png)]

2.3.1、创建子Module

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>test_mybatis_plus</artifactId><groupId>com.qianfeng</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>test_simple</artifactId></project>
  • 在qianfeng_simple模块的resources目录下新建log4j.properties:
log4j.rootLogger=DEBUG,A1log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

2.3.2、Mybatis实现查询User

第一步,在qianfeng_simple模块的resources目录下, 新建mybatis-config.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/qianfeng_mp?useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQueries=true&amp;useSSL=false"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><mapper resource="UserMapper.xml"/></mappers>
</configuration>

第二步,编写User实体对象:(这里使用lombok进行了进化bean操作)


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 用户实体类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private Long id;private String userName;private String password;private String name;private Integer age;private String email;}

第三步,编写UserMapper接口:


/*** 用户Mapper接口*/
public interface UserMapper {/*** 查询所有用户*/List<User> findAll();
}

第四步,在qianfeng_simple模块的resources目录下, 新建UserMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianfeng.mapper.UserMapper"><select id="findAll" resultType="com.qianfeng.pojo.User">select * from tb_user</select></mapper>

第五步,编写TestMybatis测试用例:


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.io.InputStream;
import java.util.List;/*** 测试类*/
public class TestMybatis {@Testpublic void testUserList() throws Exception {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> list = userMapper.findAll();for (User user : list) {System.out.println(user);}}
}

测试结果:

[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] ==>  Preparing: select * from tb_user
[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] ==> Parameters:
[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] <==      Total: 5
User(id=1, userName=null, password=123456, name=青龙, age=18, email=test1@1000phone.com)
User(id=2, userName=null, password=123456, name=白虎, age=20, email=test2@1000phone.com)
User(id=3, userName=null, password=123456, name=朱雀, age=28, email=test3@1000phone.com)
User(id=4, userName=null, password=123456, name=玄武, age=21, email=test4@1000phone.com)
User(id=5, userName=null, password=123456, name=饕鬄, age=24, email=test5@1000phone.com)

2.3.3、Mybatis+MP实现查询User

第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法:


import com.baomidou.mybatisplus.core.mapper.BaseMapper;import java.util.List;/*** 用户Mapper接口*/
public interface UserMapper extends BaseMapper<User> {/*** 查询所有用户*/List<User> findAll();
}

第二步,使用MP中的MybatisSqlSessionFactoryBuilder进行构建:

import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.qianfeng.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;import java.io.InputStream;
import java.util.List;/*** 测试Mybatis + MP*/
public class TestMybatisPlus {@Testpublic void testUserList() throws Exception {String resource = "mybatis-config.xml";InputStream resourceAsStream = Resources.getResourceAsStream(resource);//这里使用的是MP中的MybatisSqlSessionFactoryBuilderSqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(resourceAsStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> list = userMapper.findAll();for (User user : list) {System.out.println(user);}}
}

测试:

[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] ==>  Preparing: select * from tb_user
[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] ==> Parameters:
[main] [com.test.mapper.UserMapper.findAll]-[DEBUG] <==      Total: 5
User(id=1, userName=qinglong, password=123456, name=青龙, age=18, email=test1@1000phone.com)
User(id=2, userName=baihu, password=123456, name=白虎, age=20, email=test2@1000phone.com)
User(id=3, userName=zhuque, password=123456, name=朱雀, age=28, email=test3@1000phone.com)
User(id=4, userName=xuanwu, password=123456, name=玄武, age=21, email=test4@1000phone.com)
User(id=5, userName=taoti, password=123456, name=饕鬄, age=24, email=test5@1000phone.com)

简单说明:

  • 由于使用了MybatisSqlSessionFactoryBuilder进行了构建,继承的BaseMapper中的方法就载入到了SqlSession中,所以就可以直接使用相关的方法;

2.4、Spring + Mybatis + MP

引入了Spring框架,数据源、构建等工作就交给了Spring管理。

2.4.1、创建子Module

  • 在qianfeng_mybatis_plus模块上, 点击鼠标右键, 新建Model 为qianfeng_mybatis_pulus_spring
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>test_mybatis_plus</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>test_mybatis_plus_spring</artifactId><properties><spring.version>5.1.6.RELEASE</spring.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency></dependencies></project>

2.4.2、实现查询User

第一步,在test_mybatis_pulus_spring模块的resources目录下, 新建jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/qianfeng_mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
jdbc.username=root
jdbc.password=123456

第二步,在testmybatis_pulus_spring模块的resources目录下, 新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:*.properties"/><!-- 定义数据源 --><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"destroy-method="close"><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="driverClassName" value="${jdbc.driver}"/><property name="maxActive" value="10"/><property name="minIdle" value="5"/></bean><!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合--><bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/></bean><!--扫描mapper接口,使用的依然是Mybatis原生的扫描器--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.qianfeng.mapper"/></bean></beans>

第三步,编写User对象以及UserMapper接口:


import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 用户实体类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {private Long id;private String userName;private String password;private String name;private Integer age;private String email;}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** 用户Mapper接口*/
public interface UserMapper extends BaseMapper<User> {}

第四步,编写测试用例:

package com.test.test;import com.test.mapper.UserMapper;
import com.test.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectList(){List<User> users = this.userMapper.selectList(null);for (User user : users) {System.out.println(user);}}
}

测试:

User(id=1, userName=qinglong, password=123456, name=青龙, age=18, email=test1@1000phone.com)
User(id=2, userName=baihu, password=123456, name=白虎, age=20, email=test2@1000phone.com)
User(id=3, userName=zhuque, password=123456, name=朱雀, age=28, email=test3@1000phone.com)
User(id=4, userName=xuanwu, password=123456, name=玄武, age=21, email=test4@1000phone.com)
User(id=5, userName=taoti, password=123456, name=饕鬄, age=24, email=test5@1000phone.com)

2.5、SpringBoot + Mybatis + MP

使用SpringBoot将进一步的简化MP的整合

注意 : 由于使用SpringBoot需要继承parent,所以需要重新创建工程,并不是创建子Module。

2.5.1、创建工程

新建Model, Maven工程, 不选择骨架, 名字叫做 test_mp_springboot

2.5.2、导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.test</groupId><artifactId>test_mp_springboot</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version></parent><properties><!-- 项目源码及编译输出的编码 --><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><!-- 项目编译JDK版本 --><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--简化代码的工具包--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--mybatis-plus的springboot支持--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.1.1</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
  • test_mp_springboot模块的resources目录下, 新建log4j.properties:
log4j.rootLogger=DEBUG,A1log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

2.5.3、编写application.properties

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

2.5.4、编写pojo

package com.test.pojo;import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 用户实体类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {private Long id;private String userName;private String password;private String name;private Integer age;private String email;}

2.5.5、编写mapper

package com.test.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.pojo.User;public interface UserMapper extends BaseMapper<User> {}

2.5.6、编写启动类

package com.test;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** 启动类*/
@SpringBootApplication
//设置mapper接口的扫描包
@MapperScan("com.test.mapper")
public class MpApplication {public static void main(String[] args) {SpringApplication.run(MpApplication.class, args);}
}

2.5.7、编写测试用例

注意 : 此项目为springboot项目, 测试类必须放在src/test/java目录下, 千万不要放在src/main/java目录下, 否则注解@SpringBootTest找不到包.

package com.test.test;import com.test.mapper.UserMapper;
import com.test.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 {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelect() {List<User> userList = userMapper.selectList(null);for (User user : userList) {System.out.println(user);}}
}

3、通用CRUD

通过前面的学习,我们了解到通过继承BaseMapper就可以获取到各种各样的单表操作,接下来我们将详细讲解这些操作。

3.1、插入操作

3.1.1、测试用例

package com.qianfeng.test;import com.test.mapper.UserMapper;
import com.test.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 {@Autowiredprivate UserMapper userMapper;@Testpublic void testInsert() {User user = new User();user.setAge(29);user.setName("梼杌");user.setEmail("taowu@1000phone.com");user.setUserName("taowu");user.setPassword("123456");int count = userMapper.insert(user);System.out.println("=======操作了几条数据:====" + count);System.out.println("===id是:====" + user.getId());}
}

3.1.2、执行测试结果

3.1.3、ID生成策略

可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,实际是MP生成了id的值写入到了数据库。

如何设置id的生成策略呢?

MP支持的id策略:

package com.baomidou.mybatisplus.annotation;import lombok.Getter;/*** 生成ID类型枚举类*/
@Getter
public enum IdType {/*** 数据库ID自增*/AUTO(0),/*** 该类型为未设置主键类型*/NONE(1),/*** 用户输入ID* <p>该类型可以通过自己注册自动填充插件进行填充</p>*/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.test.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 {//指定id类型为使用分布式ID生成器生成@TableId(type = IdType.ID_WORKER)private Long id;private String userName;private String password;private String name;private Integer age;private String email;
}

数据插入成功:

3.1.4、@TableField

在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有2个:

1、对象中的属性名和字段名不一致的问题(非驼峰)

2、对象中的属性字段在表中不存在的问题

使用:

package com.test.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 lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 用户实体类*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {//指定id类型为使用分布式ID生成器生成@TableId(type = IdType.ID_WORKER)private Long id;private String userName;//密码字段不应该被查询出来@TableField(select = false)private String password;private String name;private Integer age;//表中字段名和实体类属性名不一致@TableField(value = "email")private String mail;//表中不存在这个字段@TableField(exist = false)private String address;}

3.2、更新操作

在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。

3.2.1、根据id更新

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testUpdateById() {User user = new User();user.setId(1352412605444091905L); //主键user.setAge(21); //更新的字段//根据id更新,更新不为null的字段userMapper.updateById(user);}}

结果:

3.2.2、根据条件更新

源码中的方法:

    /*** 根据 whereEntity 条件,更新记录** @param entity        实体对象 (set 条件值,可以为 null)* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)*/int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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 {@Autowiredprivate UserMapper userMapper;@Testpublic void testUpdate() {User user = new User();user.setAge(22); //更新的字段//更新的条件QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("id", 1352412605444091905L);//执行更新操作int result = userMapper.update(user, wrapper);System.out.println("result = " + result);}
}

关于wrapper更多的用法后面会详细讲解。

3.3、删除操作

3.3.1、deleteById

源码中的方法:

/*** 根据 ID 删除** @param id 主键ID*/
int deleteById(Serializable id);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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;/*** 普通增删改查测试* @author zhaojian*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testDeleteById() {//执行删除操作int result = userMapper.deleteById(1352412605444091905L);System.out.println("result = " + result);}
}

结果:

数据被删除。

3.3.2、deleteByMap

源码中的方法:

    /*** 根据 columnMap 条件,删除记录** @param columnMap 表字段 map 对象*/int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

测试用例:

@Test
public void testDeleteByMap() {Map<String, Object> columnMap = new HashMap<>();columnMap.put("age",29);columnMap.put("name","梼杌");//将columnMap中的元素设置为删除的条件,多个之间为and关系int result = userMapper.deleteByMap(columnMap);System.out.println("result = " + result);
}

3.3.3、delete

源码中的方法:

/*** 根据 entity 条件,删除记录** @param wrapper 实体对象封装操作类(可以为 null)*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

测试用例:

@Test
public void testDelete() {User user = new User();user.setAge(24);user.setName("饕鬄");//将实体对象进行包装,包装为操作条件QueryWrapper<User> wrapper = new QueryWrapper<>(user);int result = userMapper.delete(wrapper);System.out.println("result = " + result);
}

3.3.4、deleteBatchIds

源码中的方法:

    /*** 删除(根据ID 批量删除)** @param idList 主键ID列表(不能为 null 以及 empty)*/int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

测试用例:

@Test
public void testDeleteByMap() {//根据id集合批量删除int result = userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));System.out.println("result = " + result);
}

3.4、查询操作

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

3.4.1、selectById

源码中的方法:

    /*** 根据 ID 查询** @param id 主键ID*/T selectById(Serializable id);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectById() {//根据id查询数据User user = userMapper.selectById(4L);System.out.println("result = " + user);}}

3.4.2、selectBatchIds

源码中的方法:

/*** 查询(根据ID 批量查询)** @param idList 主键ID列表(不能为 null 以及 empty)*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试* @author zhaojian*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectBatchIds() {//根据id集合批量查询List<User> users = userMapper.selectBatchIds(Arrays.asList(2L, 3L, 4L));for (User user : users) {System.out.println(user);}}}

3.4.3、selectOne

源码中的方法:

/*** 根据 entity 条件,查询一条记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectOne() {QueryWrapper<User> wrapper = new QueryWrapper<User>();wrapper.eq("name", "玄武");//根据条件查询一条数据,如果结果超过一条会报错User user = userMapper.selectOne(wrapper);System.out.println(user);}}

3.4.4、selectCount

源码中的方法:

/*** 根据 Wrapper 条件,查询总记录数** @param queryWrapper 实体对象封装操作类(可以为 null)*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectCount() {QueryWrapper<User> wrapper = new QueryWrapper<User>();wrapper.gt("age", 20); //年龄大于20岁//根据条件查询数据条数Integer count = userMapper.selectCount(wrapper);System.out.println("count = " + count);}}

3.4.5、selectList

源码中的方法:

/*** 根据 entity 条件,查询全部记录** @param queryWrapper 实体对象封装操作类(可以为 null)*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectList() {QueryWrapper<User> wrapper = new QueryWrapper<User>();wrapper.gt("age", 20); //年龄大于20岁//根据条件查询数据List<User> users = userMapper.selectList(wrapper);for (User user : users) {System.out.println("user = " + user);}}}

3.4.6、selectPage

源码中的方法:

/*** 根据 entity 条件,查询全部记录(并分页)** @param page         分页查询条件(可以为 RowBounds.DEFAULT)* @param queryWrapper 实体对象封装操作类(可以为 null)*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

配置分页插件:

package com.test.config;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;/*** MybatisPlus分页插件配置类*/
@Configuration
//设置mapper接口的扫描包
@MapperScan("com.qianfeng.mapper")
public class MybatisPlusConfig {/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
}

测试用例:

package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelectPage() {QueryWrapper<User> wrapper = new QueryWrapper<User>();wrapper.gt("age", 20); //年龄大于20岁Page<User> page = new Page<>(1,1);//根据条件查询数据IPage<User> iPage = userMapper.selectPage(page, wrapper);//service中的方法 接口接收IPage<Emp> Page = new Page<Emp>(1, 5);IPage<Emp> empIPage = empMapper.selectPage(Page,queryWrapper);System.out.println("数据总条数:" + iPage.getTotal());System.out.println("总页数:" + iPage.getPages());List<User> users = iPage.getRecords();for (User user : users) {System.out.println("user = " + user);}}}

4、配置

在MP中有大量的配置,其中有一部分是Mybatis原生的配置,另一部分是MP的配置,详情:https://mybatis.plus/config/

下面我们对常用的配置做讲解。

4.1、基本配置

4.1.1、configLocation

MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation 中。 MyBatis Configuration 的具体内容请参考MyBatis 官方文档

Spring Boot:

mybatis-plus.config-location = classpath:mybatis-config.xml

Spring MVC:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

4.1.2、mapperLocations

MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。

Spring Boot:

mybatis-plus.mapper-locations = classpath*:mybatis/*.xml

Spring MVC:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
</bean>

Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件)

测试:

  • 项目resources目录下的 application.properties 配置文件:
spring.application.name = qianfeng-mp-springbootspring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/qianfeng_mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
  • 项目resources目录下新建mybatis目录, 在mybatis目录下新建UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianfeng.mapper.UserMapper"><select id="findById" resultType="com.qianfeng.pojo.User">select * from tb_user where id = #{id}</select></mapper>
package com.test.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.pojo.User;public interface UserMapper extends BaseMapper<User> {public User findById(Long id);
}
  • 测试用例:
package com.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testFindById() {User user = userMapper.findById(2L);System.out.println(user);}
}

4.1.3、typeAliasesPackage

MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。

Spring Boot:

mybatis-plus.type-aliases-package = com.qianfeng.pojo

Spring MVC:

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="typeAliasesPackage" value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
</bean>

4.2、进阶配置

本部分(Configuration)的配置大都为 MyBatis 原生支持的配置,这意味着您可以通过 MyBatis XML 配置文件的形式进行配置。

4.2.1、mapUnderscoreToCamelCase

  • 类型: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.2、cacheEnabled

  • 类型:boolean
  • 默认值:true

全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,默认为 true。

示例:

mybatis-plus.configuration.cache-enabled=false

4.3、DB 策略配置

4.3.1、idType

  • 类型:com.baomidou.mybatisplus.annotation.IdType
  • 默认值:ID_WORKER

全局默认主键类型,设置后,即可省略实体对象中的@TableId(type = IdType.AUTO)配置。

示例:

SpringBoot:

mybatis-plus.global-config.db-config.id-type=auto

SpringMVC:

<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合--><bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="globalConfig"><bean class="com.baomidou.mybatisplus.core.config.GlobalConfig"><property name="dbConfig"><bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"><property name="idType" value="AUTO"/></bean></property></bean></property></bean>

4.3.2、tablePrefix

  • 类型:String
  • 默认值:null

表名前缀,全局配置后可省略@TableName()配置。

SpringBoot:

mybatis-plus.global-config.db-config.table-prefix=tb_

SpringMVC:

 <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="globalConfig"><bean class="com.baomidou.mybatisplus.core.config.GlobalConfig"><property name="dbConfig"><bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"><property name="idType" value="AUTO"/><property name="tablePrefix" value="tb_"/></bean></property></bean></property></bean>

5、条件构造器

在MP中,Wrapper接口的实现类关系如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3bh0MewH-1672022032496)(Pictures/1556451302015.png)]

可以看到,AbstractWrapper和AbstractChainWrapper是重点实现,接下来我们重点学习AbstractWrapper以及其子类。

说明:

QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为

官网文档地址:https://mybatis.plus/guide/wrapper.html

5.1、allEq

5.1.1、说明

allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
  • 全部eq(或个别isNull)

个别参数说明:
params : key为数据库字段名,value为字段值
null2IsNull : 为true则在mapvaluenull时调用 isNull 方法, 为false时则忽略valuenull的字段

  • 例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 = ‘老王’``

    condition:是否执行Map中的条件,true就执行,false就查询全表

allEq(BiPredicate<R, V> filter, Map<R, V> params)
allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)

个别参数说明:
filter : 过滤函数,是否允许字段传入比对条件中
paramsnull2IsNull : 同上

  • 例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.qianfeng.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapper() {QueryWrapper<User> wrapper = new QueryWrapper<>();//设置条件Map<String,Object> params = new HashMap<>();params.put("name", "饕鬄");params.put("age", "39");params.put("password", null);//        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 = ?List<User> users = 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.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapper() {QueryWrapper<User> wrapper = new QueryWrapper<>();wrapper.eq("password", "123456").ge("age", 20).in("name", "朱雀", "玄武", "饕鬄");List<User> users = 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.qianfeng.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperLike() {QueryWrapper<User> wrapper = new QueryWrapper<>();/*** SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE user_name LIKE ? * Parameters: %q%(String)*/wrapper.like("user_name", "q");List<User> users = 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.test.test;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.mapper.UserMapper;
import com.test.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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperOrderBy() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,user_name,name,age,email AS mail FROM tb_user ORDER BY age DESC wrapper.orderByDesc("age");List<User> users = 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.qianfeng.test;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperOr() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? OR age = ? wrapper.eq("name","青龙").or().eq("age", 40);List<User> users = userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}}

5.6、select

在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。

package com.qianfeng.test;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperField() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ? wrapper.eq("name", "青龙").or().eq("age", 40).select("id", "name", "age");List<User> users = this.userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}}

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.HashMap;
import java.util.List;
import java.util.Map;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperOrderBy() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,user_name,name,age,email AS mail FROM tb_user ORDER BY age DESC wrapper.orderByDesc("age");List<User> users = 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.test.test;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperOr() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? OR age = ? wrapper.eq("name","青龙").or().eq("age", 40);List<User> users = userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}}

5.6、select

在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。

package com.test.test;/*** 普通增删改查测试*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testWrapperField() {QueryWrapper<User> wrapper = new QueryWrapper<>();//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ? wrapper.eq("name", "青龙").or().eq("age", 40).select("id", "name", "age");List<User> users = this.userMapper.selectList(wrapper);for (User user : users) {System.out.println(user);}}}

Mybatis-Plus整理知识点01相关推荐

  1. MyBatis基础学习知识点2

    本文衔接MyBatis基础学习知识点1,继续对以下两个问题进行探讨 1.dao配置文件主要是用来干什么的?如何进行配置? 2.使用测试方法测试程序运行是如何实现的?每条语句起什么作用? 目录 dao配 ...

  2. 2021-03-01低轨卫星定轨流程整理学习01

    2021-03-01低轨卫星定轨流程整理学习01(简要介绍) 一.什么是定轨? 低轨卫星精密定轨数据处理是通过低轨卫星所能够提供的观测资料以及已知的低轨卫星运动学规律通过统计的方法来确定低轨卫星在指定 ...

  3. 整理1986.01-2019.02_国际WTI原油价格日、周、月、年度数据

    整理1986.01-2019.02_国际WTI原油价格日.周.月.年度数据 数据集名称:国际WTI原油价格日.周.月.年度数据 时间范围:1986.01-2019.02 数据来源:自算 相关说明:WT ...

  4. 【Mybatis】学习笔记01:连接数据库,实现增删改

    需要数据库SQL的请跳转到文末 哔哩哔哩 萌狼蓝天[转载资料][尚硅谷][MyBatis]2022版Mybatis配套MD文档[Mybatis]学习笔记01:连接数据库,实现增删改[Mybatis]学 ...

  5. 468、Java框架122 -【Spring + SpringMVC + MyBatis - JSON】 2021.01.27

    目录 0.本知识点效果 1.jquery.min.js 2.json中文问题 3.CategoryController 4.submit.html 5.getOne.html 6.getMany.ht ...

  6. mybatis笔记整理

    前言: mybatis可以说是最容易上手的持久层框架了,相比于hibernate 而言,它都是直接用sql语句对数据库进行操作,而不是用hql,尤其是关联关系复杂的时候,mybatis更容易实现.下面 ...

  7. java个人整理知识点

    发展: 1.SE 标准版. 2.EE 企业版,基于SE. 3.ME 已经淘汰. JDK.JRE和JVM: JDK: 称为Java开发工具包( Java Development Kit).Java开发人 ...

  8. 总结了Mybatis,原来知识点也没多少嘛

    前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y Mybatis应该是国内用得最多的「数据访问层」 ...

  9. golang个人整理知识点

    环境变量: GOPATH: window下默认值路径为%USERPROFILE%/go,可以删掉新建,然后所有的项目代码放在src子目录下 GOPATH路径下有三个目录src pkg bin 具体的子 ...

最新文章

  1. mxnet中的SoftmaxCrossEntropyLoss损失函数
  2. 一级计算机基础第四套,《计算机应用基础》第四套考试与答案.doc
  3. TPS(薄板样条) 2D 插值
  4. java this$0_java中this$0的含义及用法
  5. pcb外观维修_PCB电路板维修的一些常用技法
  6. javamail读取并发送完整的html页面
  7. 关于jquery ajax发送以及php接受json数据的一点记录
  8. 欢乐纪中某B组赛【2019.1.30】The penultimate day
  9. Weblogic读不到Word文件
  10. CAFFE(FAQ.2):Ubuntu 配置caffe 框架之数据库读取,错误解决:ImportError: No module named leveldb解决办法...
  11. CentOS禁用root用户远程登录
  12. Custom Corporate Background for NetBeans Platform Applications
  13. 面试遇到不会回答的问题,如何力挽狂澜 ?
  14. C#基础知识四之override和new的区别
  15. 林毅夫1.7万字长文:我的13个经济学新见解
  16. rnn--重新温习实现MNIST手写体识别
  17. php校园学校宿舍管理系统 php毕业设计题目课题选题 php毕业设计项目作品源码(3)班主任和宿舍管理员功能
  18. 计算机系统文件夹打不开,电脑系统的文件夹打不开可以试下这两个办法
  19. c语言怎么让电脑backspace,backspace键在哪里
  20. 如何申请腾讯云免费ssl证书并部署

热门文章

  1. c语言程序设计学籍信息,c语言学籍信息管理系统设计
  2. c语言学生学籍管理修改,C语言课设之学生学籍管理系统.doc
  3. 浪潮服务器u盘安装系统_浪潮服务器系统安装怎样从光驱引导
  4. 计算机音乐谱毛不易,中国内地流行男歌手毛不易歌曲简谱精选
  5. “人生苦短,我用Python“——网络嗅探与欺骗
  6. html数据的格式是什么格式的文件,.html是什么格式的文件,html文件怎么打开
  7. macbook air 重置mysql密码
  8. Entertain Box multiset的应用
  9. html网页设计板报,html5做一个黑板报页面
  10. atitit.研发企业与团队文化的结构框架 企业文化建设方案3.0