MyBatisPlus——入门介绍

x33g5p2x  于2021-10-09 转载在 其他  
字(56.3k)|赞(0)|评价(0)|浏览(428)

本文章笔记整理来自黑马视频https://www.bilibili.com/video/BV1rE41197jR,相关资料可以在视频评论取领取。

1.MyBatis介绍

1.1.MyBatisPlus概述

(1)MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
(2)官方地址:https://mybatis.plus/或者https://mp.baomidou.com/
(3)文档地址:https://mybatis.plus/guide/或者https://mp.baomidou.com/guide/
(4)源码地址:https://github.com/baomidou/mybatis-plus
(5)Mybatis-Plus是由baomidou(苞米豆)组织开发并且开源的,码云地址为:https://gitee.com/organizations/baomidou

1.2.MyBatisPlus特性

无侵入只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
强大的 CRUD 操作内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
支持 Lambda 形式调用通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、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.3.MyBatisPlus架构

2.快速开始

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

2.1.创建数据库以及表

(1)创建名为mp的数据库,且字符集选择utf8。

(2)在mp数据库中创建一张名为tb_user的表,并且插入一些测试数据,对应的SQL语句如下:

  1. -- 创建测试表
  2. CREATE TABLE `tb_user` (
  3. `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  4. `user_name` varchar(20) NOT NULL COMMENT '用户名',
  5. `password` varchar(20) NOT NULL COMMENT '密码',
  6. `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  7. `age` int(11) DEFAULT NULL COMMENT '年龄',
  8. `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  9. PRIMARY KEY (`id`)
  10. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  11. -- 插入测试数据
  12. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES
  13. ('1', 'zhangsan', '123456', '张三', '18', 'test1@itcast.cn');
  14. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES
  15. ('2', 'lisi', '123456', '李四', '20', 'test2@itcast.cn');
  16. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES
  17. ('3', 'wangwu', '123456', '王五', '28', 'test3@itcast.cn');
  18. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES
  19. ('4', 'zhaoliu', '123456', '赵六', '21', 'test4@itcast.cn');
  20. INSERT INTO `tb_user` (`id`, `user_name`, `password`, `name`, `age`, `email`) VALUES
  21. ('5', 'sunqi', '123456', '孙七', '24', 'test5@itcast.cn');

2.2.创建工程

2.2.1.在IDEA中创建一个Maven工程

2.2.2.在pom.xml中导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>cn.itcast.mp</groupId>
  5. <artifactId>itcast-mybatis-plus</artifactId>
  6. <version>1.0-SNAPSHOT</version>
  7. <dependencies>
  8. <!-- mybatis-plus插件依赖 -->
  9. <dependency>
  10. <groupId>com.baomidou</groupId>
  11. <artifactId>mybatis-plus</artifactId>
  12. <version>3.1.1</version>
  13. </dependency>
  14. <!-- MySql连接依赖 -->
  15. <dependency>
  16. <groupId>mysql</groupId>
  17. <artifactId>mysql-connector-java</artifactId>
  18. <version>5.1.47</version>
  19. </dependency>
  20. <!-- druid连接池 -->
  21. <dependency>
  22. <groupId>com.alibaba</groupId>
  23. <artifactId>druid</artifactId>
  24. <version>1.0.11</version>
  25. </dependency>
  26. <!--简化bean代码的工具包——lombok-->
  27. <dependency>
  28. <groupId>org.projectlombok</groupId>
  29. <artifactId>lombok</artifactId>
  30. <optional>true</optional>
  31. <version>1.18.4</version>
  32. </dependency>
  33. <!--单元测试-->
  34. <dependency>
  35. <groupId>junit</groupId>
  36. <artifactId>junit</artifactId>
  37. <version>4.12</version>
  38. </dependency>
  39. <!--日志-->
  40. <dependency>
  41. <groupId>org.slf4j</groupId>
  42. <artifactId>slf4j-log4j12</artifactId>
  43. <version>1.6.4</version>
  44. </dependency>
  45. </dependencies>
  46. <build>
  47. <plugins>
  48. <!--编译项目代码-->
  49. <plugin>
  50. <groupId>org.apache.maven.plugins</groupId>
  51. <artifactId>maven-compiler-plugin</artifactId>
  52. <configuration>
  53. <source>1.8</source>
  54. <target>1.8</target>
  55. </configuration>
  56. </plugin>
  57. </plugins>
  58. </build>
  59. </project>

2.3.Mybatis+MP

2.3.1.创建子Module

在resources目录下创建日志配置文件log4j.properties

  1. log4j.rootLogger=DEBUG,A1
  2. log4j.appender.A1=org.apache.log4j.ConsoleAppender
  3. log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  4. log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

2.3.2.Mybatis实现查询User

(1)创建MyBatis全局配置文件mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <settings>
  5. <!--开启驼峰命名-->
  6. <setting name="mapUnderscoreToCamelCase" value="true"/>
  7. </settings>
  8. <environments default="development">
  9. <environment id="development">
  10. <transactionManager type="JDBC"/>
  11. <dataSource type="POOLED">
  12. <property name="driver" value="com.mysql.jdbc.Driver"/>
  13. <property name="url" value="jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQueries=true&amp;useSSL=false"/>
  14. <property name="username" value="root"/>
  15. <property name="password" value="123456"/>
  16. </dataSource>
  17. </environment>
  18. </environments>
  19. <!--注册SQL映射文件-->
  20. <mappers>
  21. <mapper resource="UserMapper.xml"/>
  22. </mappers>
  23. </configuration>

(2)创建User实体类以及UserMapper接口、UserMapper.xml文件

  1. package cn.itcast.mp.simple.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. public class User {
  9. private Long id;
  10. private String userName;
  11. private String password;
  12. private String name;
  13. private Integer age;
  14. private String email;
  15. }
  1. package cn.itcast.mp.simple.mapper;
  2. import cn.itcast.mp.simple.pojo.User;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import java.util.List;
  5. public interface UserMapper{
  6. List<User> findAll();
  7. }

(3)编写TestMybatis测试用例

  1. package cn.itcast.mp.simple;
  2. import cn.itcast.mp.simple.mapper.UserMapper;
  3. import cn.itcast.mp.simple.pojo.User;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.Test;
  9. import java.io.InputStream;
  10. import java.util.List;
  11. public class TestMybatis {
  12. @Test
  13. public void testFindAll() throws Exception{
  14. String config = "mybatis-config.xml";
  15. InputStream inputStream = Resources.getResourceAsStream(config);
  16. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  17. SqlSession sqlSession = sqlSessionFactory.openSession();
  18. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  19. //测试查询
  20. List<User> users = userMapper.findAll();
  21. for (User user : users) {
  22. System.out.println(user);
  23. }
  24. }
  25. }

结果如下:

2.3.3.Mybatis+MP实现查询User

(1)将UserMapper继承BaseMapper,这样将拥有BaseMapper中的所有方法

  1. package cn.itcast.mp.simple.mapper;
  2. import cn.itcast.mp.simple.pojo.User;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import java.util.List;
  5. public interface UserMapper extends BaseMapper<User> {
  6. List<User> findAll();
  7. }

(2)在User类上添加注解@TableName(“tb_user”),指定该实体类所对应的数据库表名(如果不添加该注解,则会出现Table ‘mp.user’ dosen’t exist的错误提示)

(3)使用MP中的MybatisSqlSessionFactoryBuilder进行构建

  1. package cn.itcast.mp.simple;
  2. import cn.itcast.mp.simple.mapper.UserMapper;
  3. import cn.itcast.mp.simple.pojo.User;
  4. import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  9. import org.junit.Test;
  10. import java.io.InputStream;
  11. import java.util.List;
  12. public class TestMybatisPlus {
  13. @Test
  14. public void testFindAll() throws Exception{
  15. String config = "mybatis-config.xml";
  16. InputStream inputStream = Resources.getResourceAsStream(config);
  17. //这里使用的是MP中的MybatisSqlSessionFactoryBuilder
  18. SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
  19. SqlSession sqlSession = sqlSessionFactory.openSession();
  20. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  21. //测试查询
  22. // List<User> users = userMapper.findAll();
  23. List<User> users = userMapper.selectList(null);
  24. for (User user : users) {
  25. System.out.println(user);
  26. }
  27. }
  28. }

结果如下:

2.4.Spring + Mybatis + MP

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

2.4.1.创建子Module

与上面一样,创建一个名为itcast-mybatis-plus-spring的子Module,并在pom.xml中导入Spring的相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <parent>
  4. <artifactId>itcast-mybatis-plus</artifactId>
  5. <groupId>cn.itcast.mp</groupId>
  6. <version>1.0-SNAPSHOT</version>
  7. </parent>
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>itcast-mybatis-plus-spring</artifactId>
  10. <properties>
  11. <spring.version>5.1.6.RELEASE</spring.version>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.springframework</groupId>
  16. <artifactId>spring-webmvc</artifactId>
  17. <version>${spring.version}</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework</groupId>
  21. <artifactId>spring-jdbc</artifactId>
  22. <version>${spring.version}</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-test</artifactId>
  27. <version>${spring.version}</version>
  28. </dependency>
  29. </dependencies>
  30. </project>

2.4.2.实现查询User

(1)编写数据库配置文件jdbc.properties以及日志配置文件log4j.properties

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
  3. jdbc.username=root
  4. jdbc.password=123456
  1. log4j.rootLogger=DEBUG,A1
  2. log4j.appender.A1=org.apache.log4j.ConsoleAppender
  3. log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  4. log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

(2)编写Spring配置文件applicationContext.xml以及MyBatis配置文件mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  3. <context:property-placeholder location="classpath:jdbc.properties"/>
  4. <!-- 定义数据源 -->
  5. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
  6. <property name="url" value="${jdbc.url}"/>
  7. <property name="username" value="${jdbc.username}"/>
  8. <property name="password" value="${jdbc.password}"/>
  9. <property name="driverClassName" value="${jdbc.driver}"/>
  10. <property name="maxActive" value="10"/>
  11. <property name="minIdle" value="5"/>
  12. </bean>
  13. <!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
  14. <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
  15. <property name="dataSource" ref="dataSource"/>
  16. <property name="configLocation" value="classpath:mybatis-config.xml"/>
  17. <property name="globalConfig">
  18. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
  19. <property name="dbConfig">
  20. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
  21. <property name="idType" value="AUTO"/>
  22. </bean>
  23. </property>
  24. </bean>
  25. </property>
  26. </bean>
  27. <!--扫描mapper接口,使用的依然是Mybatis原生的扫描器-->
  28. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  29. <property name="basePackage" value="cn.itcast.mp.simple.mapper"/>
  30. </bean>
  31. </beans>
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <settings>
  5. <!--开启驼峰命名-->
  6. <setting name="mapUnderscoreToCamelCase" value="true"/>
  7. </settings>
  8. </configuration>

(3)创建User实体类以及UserMapper接口(与上面的基本一样,可以直接复制)
(4)编写测试用例

  1. package cn.itcast.mp.simple;
  2. import cn.itcast.mp.simple.mapper.UserMapper;
  3. import cn.itcast.mp.simple.pojo.User;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import java.util.List;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  12. public class TestMybatisSpring {
  13. @Autowired
  14. private UserMapper userMapper;
  15. @Test
  16. public void testSelectList(){
  17. //不带条件查询用户,即查询所有使用户
  18. List<User> users = this.userMapper.selectList(null);
  19. for (User user : users) {
  20. System.out.println(user);
  21. }
  22. }
  23. }

结果如下:

2.5.SpringBoot + Mybatis + MP

使用SpringBoot将进一步的简化MP的整合,需要注意的是,由于使用SpringBoot需要继承parent,所以需要重新创建工程,并不是创建子Module

2.5.1.创建工程

(1)创建一个名为itcast-mp-springboot的工程

(2)在pom.xml中导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.4.RELEASE</version>
  8. </parent>
  9. <groupId>cn.itcast.mp</groupId>
  10. <artifactId>itcast-mp-springboot</artifactId>
  11. <version>1.0-SNAPSHOT</version>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter</artifactId>
  16. <exclusions>
  17. <exclusion>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-logging</artifactId>
  20. </exclusion>
  21. </exclusions>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. <!--简化代码的工具包-->
  29. <dependency>
  30. <groupId>org.projectlombok</groupId>
  31. <artifactId>lombok</artifactId>
  32. <optional>true</optional>
  33. </dependency>
  34. <!--mybatis-plus的springboot支持-->
  35. <dependency>
  36. <groupId>com.baomidou</groupId>
  37. <artifactId>mybatis-plus-boot-starter</artifactId>
  38. <version>3.1.1</version>
  39. </dependency>
  40. <!--mysql驱动-->
  41. <dependency>
  42. <groupId>mysql</groupId>
  43. <artifactId>mysql-connector-java</artifactId>
  44. <version>5.1.47</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.slf4j</groupId>
  48. <artifactId>slf4j-log4j12</artifactId>
  49. </dependency>
  50. </dependencies>
  51. <build>
  52. <plugins>
  53. <plugin>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-maven-plugin</artifactId>
  56. </plugin>
  57. </plugins>
  58. </build>
  59. </project>

2.5.2.编写相关的配置文件

(1)日志配置文件log4j.properties

  1. log4j.rootLogger=DEBUG,A1
  2. log4j.appender.A1=org.apache.log4j.ConsoleAppender
  3. log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  4. log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

(2)SpringBoot全局配置文件application.properties

  1. spring.application.name = itcast-mp-springboot
  2. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  3. spring.datasource.url=jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
  4. spring.datasource.username=root
  5. spring.datasource.password=123456

(3)创建User实体类以及UserMapper接口(与上面的基本一样,可以直接复制)
(4)编写SpringBoot启动类

  1. package cn.itcast.mp;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包
  6. @SpringBootApplication
  7. public class MyApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(MyApplication.class, args);
  10. }
  11. }

(4)编写测试用例

  1. package cn.itcast.mp;
  2. import cn.itcast.mp.mapper.UserMapper;
  3. import cn.itcast.mp.pojo.User;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import java.util.List;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @SpringBootTest
  12. public class TestMybatisSpringBoot {
  13. @Autowired
  14. private UserMapper userMapper;
  15. @Test
  16. public void testSelectList(){
  17. List<User> users = this.userMapper.selectList(null);
  18. for (User user : users) {
  19. System.out.println(user);
  20. }
  21. }
  22. }

结果如下:

3.通用CRUD

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

3.1.插入操作——insert

3.1.1.方法定义

  1. /** * 插入一条记录 * * @param entity 实体对象 */
  2. int insert(T entity);

3.1.2.编写测试方法进行测试

  1. package cn.itcast.mp;
  2. import cn.itcast.mp.mapper.UserMapper;
  3. import cn.itcast.mp.pojo.User;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. public class TestUserMapper {
  12. @Autowired
  13. private UserMapper userMapper;
  14. @Test
  15. public void testInsert() {
  16. User user = new User();
  17. user.setUserName("xiaowang");
  18. user.setPassword("123456");
  19. user.setName("小王");
  20. user.setAge(21);
  21. user.setEmail("xiaowang@163.com");
  22. //result:数据库受影响的行数
  23. int result = this.userMapper.insert(user);
  24. System.out.println("result => " + result);
  25. //获取自增长后的id值, 自增长后的id值会回填到user对象中
  26. System.out.println("id => " + user.getId());
  27. }
  28. }

测试结果如下:

可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,而实际是MP自动生成的id值写入到了数据库之中。 所以应该设置id的生成策略,MP支持的id策略如下:

  1. /* * Copyright (c) 2011-2020, baomidou (jobob@qq.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */
  2. package com.baomidou.mybatisplus.annotation;
  3. import lombok.Getter;
  4. /** * 生成ID类型枚举类 * * @author hubin * @since 2015-11-10 */
  5. @Getter
  6. public enum IdType {
  7. /** * 数据库ID自增 */
  8. AUTO(0),
  9. /** * 该类型为未设置主键类型 */
  10. NONE(1),
  11. /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */
  12. INPUT(2),
  13. /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
  14. /** * 全局唯一ID (idWorker) */
  15. ID_WORKER(3),
  16. /** * 全局唯一ID (UUID) */
  17. UUID(4),
  18. /** * 字符串全局唯一ID (idWorker 的字符串表示) */
  19. ID_WORKER_STR(5);
  20. private final int key;
  21. IdType(int key) {
  22. this.key = key;
  23. }
  24. }

所以应该在User类中指定id的类型:

此外,还需要在数据库中修改tb_user表中id字段的下一个自增值。

最后,再次进行测试

3.1.4.@TableField注解

在MP中通过@TableField注解可以指定字段的一些属性,常常解决的问题有以下两个:
(1)对象中的属性名和字段名不一致的问题(非驼峰命名);
(2)对象中的属性字段在表中不存在的问题;

  1. package cn.itcast.mp.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import lombok.AllArgsConstructor;
  7. import lombok.Data;
  8. import lombok.NoArgsConstructor;
  9. @Data
  10. @NoArgsConstructor
  11. @AllArgsConstructor
  12. //@TableName("tb_user")
  13. public class User {
  14. @TableId(type = IdType.AUTO)
  15. private Long id;
  16. private String userName;
  17. @TableField(select = false) //查询时不返回该字段的值
  18. private String password;
  19. private String name;
  20. private Integer age;
  21. @TableField(value = "email") //指定数据表中字段名
  22. private String mail;
  23. @TableField(exist = false) //在数据库表中是不存在的
  24. private String address;
  25. }

3.2.更新操作

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

3.2.1.根据id更新——updateById

(1)方法定义

  1. /** * 根据 ID 修改 * * @param entity 实体对象 */
  2. int updateById(@Param(Constants.ENTITY) T entity);

(2)编写测试代码

  1. @Test
  2. public void testUpdateById(){
  3. User user = new User();
  4. user.setId(1L);
  5. user.setPassword("111111");
  6. user.setEmail("111@163.com");
  7. //将id为1的用户的密码改为111111、邮箱改为111@163.com
  8. int result = this.userMapper.updateById(user);
  9. System.out.println("result => " + result);
  10. }

3.2.2.根据条件更新——update

(1)方法定义

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

(2)编写测试代码
① 通过QueryWrapper进行更新:

  1. @Test
  2. public void testUpdate1(){
  3. User user = new User();
  4. user.setPassword("888888");
  5. user.setAge(29);
  6. QueryWrapper<User> wrapper = new QueryWrapper<>();
  7. //匹配user_name = zhangsan 的用户数据
  8. wrapper.eq("user_name", "zhangsan");
  9. /* 上面的操作相当于SQL语句: update tb_user set password = '888888' , age = 29 where user_name = 'zhangsan' */
  10. int result = this.userMapper.update(user,wrapper);
  11. System.out.println("result => " + result);
  12. }

② 通过UpdateWrapper进行更新:

  1. @Test
  2. public void testUpdate2() {
  3. UpdateWrapper<User> wrapper = new UpdateWrapper<>();
  4. wrapper.set("age", 29).set("password", "888888") //更新的字段
  5. .eq("user_name", "zhangsan"); //更新的条件
  6. int result = this.userMapper.update(null, wrapper);
  7. System.out.println("result => " + result);
  8. }

3.3.删除操作

3.3.1.根据id删除——deleteById

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testDeleteById(){
  3. // 根据id删除数据
  4. int result = this.userMapper.deleteById(6L);
  5. System.out.println("result => " + result);
  6. }

3.3.2.根据条件删除——deleteByMap

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testDeleteByMap(){
  3. Map<String,Object> map = new HashMap<>();
  4. map.put("user_name", "xiaowang");
  5. map.put("password", "123456");
  6. //根据map删除数据,多条件之间是and关系
  7. int result = this.userMapper.deleteByMap(map);
  8. System.out.println("result => " + result);
  9. }

3.3.3.根据条件删除——delete

(1)方法定义

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

(2)编写测试代码
① 方式一

  1. @Test
  2. public void testDelete1(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. wrapper.eq("user_name", "caocao1")
  5. .eq("password", "123456"); //删除的条件
  6. int result = this.userMapper.delete(wrapper);
  7. System.out.println("result => " + result);
  8. }

② 方式二(推荐使用)

  1. @Test
  2. public void testDelete2(){
  3. User user = new User();
  4. user.setPassword("123456");
  5. user.setUserName("xiaowang");
  6. QueryWrapper<User> wrapper = new QueryWrapper<>(user);
  7. // 根据包装条件做删除
  8. int result = this.userMapper.delete(wrapper);
  9. System.out.println("result => " + result);
  10. }

3.3.3.批量删除——deleteBatchIds

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testDeleteBatchIds(){
  3. // 根据id批量删除数据
  4. int result = this.userMapper.deleteBatchIds(Arrays.asList(8L, 9L));
  5. System.out.println("result => " + result);
  6. }

3.4.查询操作

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

3.4.1.根据id查询——selectById

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testSelectById() {
  3. //根据id查询数据
  4. User user = this.userMapper.selectById(2L);
  5. System.out.println("result = " + user);
  6. }

3.4.2.批量查询——selectBatchIds

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testSelectBatchIds(){
  3. // 根据id批量查询数据
  4. List<User> users = this.userMapper.selectBatchIds(Arrays.asList(2L, 3L, 4L, 100L));
  5. for (User user : users) {
  6. System.out.println(user);
  7. }
  8. }

3.4.3.查询单条数据——selectOne

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testSelectOne(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. //查询条件
  5. wrapper.eq("password", "111111");
  6. User user = this.userMapper.selectOne(wrapper);
  7. System.out.println(user);
  8. }

注:当查询的数据超过一条时(例如有4条数据),会抛出如下异常:

  1. org.mybatis.spring.MyBatisSystemException:
  2. nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4

3.4.4.查询数据条数——selectCount

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testSelectCount(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. wrapper.gt("age", 24); // 条件:年龄大于20岁的用户
  5. //根据条件查询数据条数
  6. Integer count = this.userMapper.selectCount(wrapper);
  7. System.out.println("count => " + count);
  8. }

3.4.5.查询数据列表——selectList

(1)方法定义

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

(2)编写测试代码

  1. @Test
  2. public void testSelectList(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. //设置查询条件
  5. wrapper.like("email", "itcast");
  6. List<User> users = this.userMapper.selectList(wrapper);
  7. for (User user : users) {
  8. System.out.println(user);
  9. }
  10. }

3.4.6.分页查询数据——selectPage

(1)方法定义

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

  1. /* * Copyright (c) 2011-2020, baomidou (jobob@qq.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */
  2. package com.baomidou.mybatisplus.extension.plugins.pagination;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  5. import java.util.Collections;
  6. import java.util.List;
  7. /** * 简单分页模型 * * @author hubin * @since 2018-06-09 */
  8. public class Page<T> implements IPage<T> {
  9. private static final long serialVersionUID = 8545996863226528798L;
  10. /** * 查询数据列表 */
  11. private List<T> records = Collections.emptyList();
  12. /** * 总数 */
  13. private long total = 0;
  14. /** * 每页显示条数,默认 10 */
  15. private long size = 10;
  16. /** * 当前页 */
  17. private long current = 1;
  18. /** * SQL 排序 ASC 数组 */
  19. private String[] ascs;
  20. /** * SQL 排序 DESC 数组 */
  21. private String[] descs;
  22. /** * 自动优化 COUNT SQL */
  23. private boolean optimizeCountSql = true;
  24. /** * 是否进行 count 查询 */
  25. private boolean isSearchCount = true;
  26. public Page() {
  27. // to do nothing
  28. }
  29. /** * 分页构造函数 * * @param current 当前页 * @param size 每页显示条数 */
  30. public Page(long current, long size) {
  31. this(current, size, 0);
  32. }
  33. public Page(long current, long size, long total) {
  34. this(current, size, total, true);
  35. }
  36. public Page(long current, long size, boolean isSearchCount) {
  37. this(current, size, 0, isSearchCount);
  38. }
  39. public Page(long current, long size, long total, boolean isSearchCount) {
  40. if (current > 1) {
  41. this.current = current;
  42. }
  43. this.size = size;
  44. this.total = total;
  45. this.isSearchCount = isSearchCount;
  46. }
  47. /** * 是否存在上一页 * * @return true / false */
  48. public boolean hasPrevious() {
  49. return this.current > 1;
  50. }
  51. /** * 是否存在下一页 * * @return true / false */
  52. public boolean hasNext() {
  53. return this.current < this.getPages();
  54. }
  55. @Override
  56. public List<T> getRecords() {
  57. return this.records;
  58. }
  59. @Override
  60. public Page<T> setRecords(List<T> records) {
  61. this.records = records;
  62. return this;
  63. }
  64. @Override
  65. public long getTotal() {
  66. return this.total;
  67. }
  68. @Override
  69. public Page<T> setTotal(long total) {
  70. this.total = total;
  71. return this;
  72. }
  73. @Override
  74. public long getSize() {
  75. return this.size;
  76. }
  77. @Override
  78. public Page<T> setSize(long size) {
  79. this.size = size;
  80. return this;
  81. }
  82. @Override
  83. public long getCurrent() {
  84. return this.current;
  85. }
  86. @Override
  87. public Page<T> setCurrent(long current) {
  88. this.current = current;
  89. return this;
  90. }
  91. @Override
  92. public String[] ascs() {
  93. return ascs;
  94. }
  95. public Page<T> setAscs(List<String> ascs) {
  96. if (CollectionUtils.isNotEmpty(ascs)) {
  97. this.ascs = ascs.toArray(new String[0]);
  98. }
  99. return this;
  100. }
  101. /** * 升序 * * @param ascs 多个升序字段 */
  102. public Page<T> setAsc(String... ascs) {
  103. this.ascs = ascs;
  104. return this;
  105. }
  106. @Override
  107. public String[] descs() {
  108. return descs;
  109. }
  110. public Page<T> setDescs(List<String> descs) {
  111. if (CollectionUtils.isNotEmpty(descs)) {
  112. this.descs = descs.toArray(new String[0]);
  113. }
  114. return this;
  115. }
  116. /** * 降序 * * @param descs 多个降序字段 */
  117. public Page<T> setDesc(String... descs) {
  118. this.descs = descs;
  119. return this;
  120. }
  121. @Override
  122. public boolean optimizeCountSql() {
  123. return optimizeCountSql;
  124. }
  125. @Override
  126. public boolean isSearchCount() {
  127. if (total < 0) {
  128. return false;
  129. }
  130. return isSearchCount;
  131. }
  132. public Page<T> setSearchCount(boolean isSearchCount) {
  133. this.isSearchCount = isSearchCount;
  134. return this;
  135. }
  136. public Page<T> setOptimizeCountSql(boolean optimizeCountSql) {
  137. this.optimizeCountSql = optimizeCountSql;
  138. return this;
  139. }
  140. }

(2)配置分页插件

  1. package cn.itcast.mp;
  2. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. //@Configuration:标注这是一个配置类
  7. @Configuration
  8. @MapperScan("cn.itcast.mp.mapper") //设置mapper接口的扫描包,也可以标注在SpringBoot启动类上
  9. public class MybatisPlusConfig {
  10. //配置分页插件
  11. @Bean
  12. public PaginationInterceptor paginationInterceptor(){
  13. return new PaginationInterceptor();
  14. }
  15. }

以上是在SpringBoot中的配置类中进行分页插件的配置,其实也可以在MyBatis的全局配置文件中进行配置。

  1. <plugins>
  2. <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>
  3. </plugins>

(3)编写测试代码

  1. @Test
  2. public void testSelectPage(){
  3. //查询第三页,查询2条数据
  4. Page<User> page = new Page<>(3,2);
  5. QueryWrapper<User> wrapper = new QueryWrapper<>();
  6. //设置查询条件
  7. wrapper.like("email", "itcast");
  8. IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
  9. System.out.println("数据总条数: " + iPage.getTotal());
  10. System.out.println("数据总页数: " + iPage.getPages());
  11. System.out.println("当前页数: " + iPage.getCurrent());
  12. //当前页数的所有记录
  13. List<User> records = iPage.getRecords();
  14. for (User record : records) {
  15. System.out.println(record);
  16. }
  17. }

数据库中的数据如下:

查询结果如下:

4.配置

在MP中有大量的配置,其中有一部分是Mybatis原生的配置,另一部分是MP的配置,详情请见官方文档https://mp.baomidou.com/config/

4.1.基本配置

4.1.1.configLocation

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

  1. # 指定MyBatis全局的配置文件
  2. mybatis-plus.config-location = classpath:mybatis-config.xml

(2)SpringMVC

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

4.1.2.mapperLocations

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

  1. # 指定Mapper.xml文件的路径
  2. mybatis-plus.mapper-locations = classpath*:mybatis/*.xml

(2)SpringMVC

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

4.1.3.typeAliasesPackage

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

  1. mybatis-plus.type-aliases-package = cn.itcast.mp.pojo

(2)SpringMVC

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

4.2.进阶配置

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

4.2.1.mapUnderscoreToCamelCase

mapUnderscoreToCamelCase,即是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射。类型为boolean,默认值为 true。
注意:此属性在 MyBatis 中原默认值为 false,在 MyBatis-Plus 中,此属性也将用于生成最终的 SQL 的 select body,如果数据库命名符合规则,则无需使用 @TableField 注解指定数据库字段名。
(1)SpringBoot

  1. #开启自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
  2. mybatis-plus.configuration.map-underscore-to-camel-case=true

(2)MyBatis

  1. <settings>
  2. <!--开启驼峰命名-->
  3. <setting name="mapUnderscoreToCamelCase" value="true"/>
  4. </settings>

4.2.2.cacheEnabled

cacheEnabled,即全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存,类型为boolean,默认值为 true。
(1)SpringBoot

  1. mybatis-plus.configuration.cache-enabled=false

(2)MyBatis

  1. <settings>
  2. <!--关闭缓存-->
  3. <setting name="cacheEnabled" value="false"/>
  4. </settings>

4.3.DB 策略配置

4.3.1.idType

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

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

  1. # 全局的id自增策略
  2. mybatis-plus.global-config.db-config.id-type=auto

(2)SpringMVC

  1. <!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
  2. <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
  3. <property name="dataSource" ref="dataSource"/>
  4. <property name="globalConfig">
  5. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
  6. <property name="dbConfig">
  7. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
  8. <property name="idType" value="AUTO"/>
  9. </bean>
  10. </property>
  11. </bean>
  12. </property>
  13. </bean>

4.3.2.tablePrefix

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

  1. # 全局的表名的前缀
  2. mybatis-plus.global-config.db-config.table-prefix=tb_

(2)SpringMVC

  1. <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
  2. <property name="dataSource" ref="dataSource"/>
  3. <property name="globalConfig">
  4. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
  5. <property name="dbConfig">
  6. <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
  7. <property name="idType" value="AUTO"/>
  8. <property name="tablePrefix" value="tb_"/>
  9. </bean>
  10. </property>
  11. </bean>
  12. </property>
  13. </bean>

5.条件构造器

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

可以看到,AbstractWrapper和AbstractChainWrapper是重点实现,接下来重点学习AbstractWrapper以及其子类。条件构造器的官网文档地址为:https://mp.baomidou.com/guide/wrapper.html
说明:QueryWrapper(LambdaQueryWrapper) 和UpdateWrapper(LambdaUpdateWrapper) 的父类用于生成sql的where条件,entity属性也用于生成sql的where条件。但entity生成的where条件与使用各个api生成的where条件没有任何关联行为

5.1.allEq

(1)说明

  1. allEq(Map<R, V> params)
  2. allEq(Map<R, V> params, boolean null2IsNull)
  3. allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
  4. allEq(BiPredicate<R, V> filter, Map<R, V> params)
  5. allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
  6. allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)

部分参数说明:
params: key 为数据库字段名,value为字段值。
null2IsNull: 为 true时,则在map的value为null时调用isNull方法;为false时,则忽略 value为null时的条件。

  1. 1: allEq({id:1,name:"老王",age:null}) ---> id = 1 and name = '老王' and age is null
  2. 2: allEq({id:1,name:"老王",age:null}, false) ---> id = 1 and name = '老王'

filter: 过滤函数,是否允许字段传入比对条件中 params
(2)编写测试用例

  1. @Test
  2. public void testAlleq(){
  3. Map<String,Object> params = new HashMap<>();
  4. params.put("name", "李四");
  5. params.put("age", "20");
  6. params.put("password", null);
  7. QueryWrapper<User> wrapper = new QueryWrapper<>();
  8. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE password IS NULL AND name = ? AND age = ?
  9. //wrapper.allEq(params);
  10. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE name = ? AND age = ?
  11. //wrapper.allEq(params,false);
  12. //只有age字段比对成功
  13. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE age = ?
  14. //wrapper.allEq((k,v)->(k.equals("age") || k.equals("id")),params);
  15. //age字段和name字段比对成功
  16. //Preparing: SELECT id,user_name,password,name,age,email FROM tb_user WHERE name = ? AND age = ?
  17. wrapper.allEq((k, v) -> (k.equals("age") || k.equals("id") || k.equals("name")) , params);
  18. List<User> users = this.userMapper.selectList(wrapper);
  19. for (User user : users) {
  20. System.out.println(user);
  21. }
  22. }

5.2.基本比较操作

(1)说明

eq等于 =
ne不等于 <>
gt大于 >
ge大于等于 >=
lt小于 <
le小于等于 <=
betweenBETWEEN 值1 AND 值2
notBetweenNOT BETWEEN 值1 AND 值2
in字段 IN (value.get(0), value.get(1), …)
notIn字段 NOT IN (v0, v1, …)

(2)编写测试用例

  1. @Test
  2. public void testEq() {
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. //SELECT id,user_name,password,name,age,email FROM tb_user WHERE password = ? AND age >= ? AND name IN (?,?,?)
  5. wrapper.eq("password", "123456")
  6. .ge("age", 20)
  7. .in("name", "李四", "王五", "赵六");
  8. List<User> users = this.userMapper.selectList(wrapper);
  9. for (User user : users) {
  10. System.out.println(user);
  11. }
  12. }

5.3.模糊查询

(1)说明

likeLIKE ‘%值%’,例:like(“name”, “王”) —> name like ‘%王%’
notLikeNOT LIKE ‘%值%’,例: notLike(“name”, “王”) —> name not like ‘%王%’
likeLeftLIKE ‘%值’,例: likeLeft(“name”, “王”) —> name like ‘%王’
likeRightLIKE ‘值%’,例: likeRight(“name”, “王”) —> name like ‘王%’

(2)编写测试用例

  1. @Test
  2. public void testLike(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. // SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name LIKE ?
  5. // 参数:%五(String)
  6. wrapper.likeLeft("name", "五");
  7. List<User> users = this.userMapper.selectList(wrapper);
  8. for (User user : users) {
  9. System.out.println(user);
  10. }
  11. }

5.4.排序

(1)说明

orderBy排序:ORDER BY 字段, …
orderByAscORDER BY 字段, … ASC
orderByDescORDER BY 字段, … ASC

(2)编写测试用例

  1. @Test
  2. public void testOrderByAgeDesc(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. //按照年龄倒序排序
  5. wrapper.orderByDesc("age");
  6. List<User> users = this.userMapper.selectList(wrapper);
  7. for (User user : users) {
  8. System.out.println(user);
  9. }
  10. }

5.5.逻辑查询

(1)说明

or拼接 OR,主动调用 or 表示紧接着下一个方法不是用 and 连接!(不调用 or 则默认为使用 and 连接)
andAND 嵌套,例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”)) —> and (name = ‘李白’ and status<> ‘活着’)

(2)编写测试用例

  1. @Test
  2. public void testOr(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. // SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? OR age = ?
  5. wrapper.eq("name", "王五").or().eq("age", 21);
  6. List<User> users = this.userMapper.selectList(wrapper);
  7. for (User user : users) {
  8. System.out.println(user);
  9. }
  10. }

5.6.select

(1)说明
在MP查询中,默认查询所有的字段,如果有需要也可以通过select方法进行指定字段。
(2)编写测试用例

  1. @Test
  2. public void testSelect(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. //SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
  5. wrapper.eq("name", "王五")
  6. .or()
  7. .eq("age", 21)
  8. .select("id","name","age"); //指定查询的字段
  9. List<User> users = this.userMapper.selectList(wrapper);
  10. for (User user : users) {
  11. System.out.println(user);
  12. }
  13. }

6.ActiveRecord

6.1.ActiveRecord介绍

(1)ActiveRecord属于ORM(对象关系映射)层,由Rails最早提出,遵循标准的ORM模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很大程度的快速实现模型的操作,而且简洁易懂。
(2)ActiveRecord的主要思想是:
① 每一个数据库表对应创建一个类,类的每一个对象实例对应于数据库中表的一行记录;通常表的每个字段在类中都有相应的Field;
② ActiveRecord同时负责把自己持久化,在ActiveRecord中封装了对数据库的CURD;
③ ActiveRecord是一种领域模型(Domain Model),封装了部分业务逻辑;
(3)ActiveRecord(简称AR)一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言,对于ActiveRecord 往往只能感叹其优雅,所以我们开发团队也在 AR 道路上进行了一定的探索。

6.2.AR快速入门

(1)在MP中,开启AR非常简单,只需要将实体对象继承Model即可

  1. package cn.itcast.mp.pojo;
  2. import com.baomidou.mybatisplus.extension.activerecord.Model;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. @Data
  7. @NoArgsConstructor
  8. @AllArgsConstructor
  9. //@TableName("tb_user")
  10. public class User extends Model<User>{
  11. //@TableId(type = IdType.AUTO)
  12. private Long id;
  13. private String userName;
  14. private String password;
  15. private String name;
  16. private Integer age;
  17. private String email;
  18. }

(2)编写测试代码

  1. @Test
  2. public void testSelectById(){
  3. User user = new User();
  4. user.setId(2L);
  5. //不需要显示地注入UserMapper
  6. User user1 = user.selectById();
  7. System.out.println(user1);
  8. }

7.插件

7.1.MyBatis的插件机制

有关Mybatis中的插件机制方面的知识,作者已经在MyBatis3——入门介绍这篇文章的第10节进行了总结,有需要的读者可以前往查看你,所以此处不再赘述。

7.2.SQL执行分析插件

MP提供了对SQL执行的分析插件,可用作阻断全表更新、删除的操作(注意:该插件仅适用于开发环境,不适用于生产环境

7.2.1.配置SQL分析插件

下面是在SpringBoot项目的配置类中进行的配置。

  1. @Bean //SQL分析插件
  2. public SqlExplainInterceptor sqlExplainInterceptor(){
  3. SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
  4. List<ISqlParser> list = new ArrayList<>();
  5. list.add(new BlockAttackSqlParser()); //全表更新、删除的阻断器
  6. sqlExplainInterceptor.setSqlParserList(list);
  7. return sqlExplainInterceptor;
  8. }

7.2.2.编写测试代码

  1. @Test
  2. public void testUpdateAll(){
  3. User user = new User();
  4. user.setAge(31); // 更新的数据
  5. //全表更新,但是这对SQL执行分析插件来说是不可取的
  6. boolean result = user.update(null);
  7. System.out.println("result => " + result);
  8. }

由于SQL执行分析插件的配置,上述测试代码中的全表更新操作是会被阻断的:

  1. org.apache.ibatis.exceptions.PersistenceException:
  2. ### Error updating database. Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation
  3. ### Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: Prohibition of table update operation

7.3.SQL性能分析插件

SQL性能分析拦截器,用于输出每条 SQL 语句及其执行时间,可以设置最大执行时间,超过时间会抛出异常(该插件只用于开发环境,不建议生产环境使用)。

7.3.1.配置SQL性能分析插件

下面是在MyBatis的全局配置文件mybatis-config.xml中进行的配置。

  1. <plugins>
  2. <!--配置SQL性能分析插件-->
  3. <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
  4. <!--最大执行时间,单位为毫秒-->
  5. <property name="maxTime" value="100"/>
  6. <!--对输出的SQL做格式化,默认为false-->
  7. <property name="format" value="true"/>
  8. </plugin>
  9. </plugins>

7.3.2.编写测试代码

  1. @Test
  2. public void testSelectById(){
  3. User user = new User();
  4. user.setId(2L);
  5. //不需要显示地注入UserMapper
  6. User user1 = user.selectById();
  7. System.out.println(user1);
  8. }

通过上面的结果可以看到,执行时间为5ms。如果将maxTime设置为1,那么,该操作会抛出如下异常。

  1. org.apache.ibatis.exceptions.PersistenceException:
  2. ### Error querying database. Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: The SQL execution time is too large, please optimize !
  3. ### The error may exist in cn/itcast/mp/mapper/UserMapper.java (best guess)
  4. ### The error may involve cn.itcast.mp.mapper.UserMapper.selectById
  5. ### The error occurred while handling results
  6. ### SQL: SELECT id,user_name,password,name,age,email FROM tb_user WHERE id=?
  7. ### Cause: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: The SQL execution time is too large, please optimize !

7.4.乐观锁插件

7.4.1.乐观锁介绍

(1)乐观锁的目的在于当要更新一条记录的时候,希望这条记录没有被别人更新。
(2)乐观锁实现方式:
① 取出记录时,获取当前version
② 更新时,带上这个version
③ 执行更新时, set version = newVersion where version = oldVersion
④ 如果version不对,则更新失败

7.4.2.插件配置方式

在以下三种方式中任选其一进行配置即可。
(1)在SpringBoot项目的自定义配置类中进行配置

  1. @Bean
  2. public OptimisticLockerInterceptor optimisticLockerInterceptor() {
  3. return new OptimisticLockerInterceptor();
  4. }

(2)在Spring的配置文件中进行配置

  1. <bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

(3)在Mybatis的全局配置文件mybatis-config.xml中进行配置

  1. <plugins>
  2. <!--配置乐观锁插件-->
  3. <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"></plugin>
  4. </plugins>

7.4.3.注解实体字段

(1)为tb_user表添加version字段,并且设置初始值为1

  1. ALTER TABLE `tb_user` ADD COLUMN `version` int(10) NULL AFTER `email`;
  2. UPDATE `tb_user` SET `version`='1';

(2)为User实体对象添加version字段,并且添加@Version注解

  1. //乐观锁的版本字段
  2. @Version
  3. private Integer version;

7.4.4.编写测试代码

  1. @Test
  2. public void testUpdateVersion(){
  3. User user = new User();
  4. user.setId(2L);// 查询条件
  5. User userVersion = user.selectById();
  6. user.setAge(23); // 更新的数据
  7. user.setVersion(userVersion.getVersion()); // 当前的版本信息
  8. boolean result = user.updateById();
  9. System.out.println("result => " + result);
  10. }

7.4.5.特别说明

(1)版本version支持的数据类型只有:int、Integer、long、Long、Date、Timestamp、LocalDateTime。
(2)整数类型下 newVersion = oldVersion + 1
(3)newVersion 会回写到 entity 中
(4)仅支持 updateById(id) 与 update(entity, wrapper) 方法
(5)在 update(entity, wrapper) 方法下, wrapper 不能复用!

8.Sql 注入器

在MP中,通过AbstractSqlInjector将BaseMapper中的方法注入到了Mybatis容器,这样这些方法才可以正常执行。那么,如果需要扩充BaseMapper中的方法,又应该如何实现呢?下面将以扩展findAll方法为例进行展开学习。

8.1.编写MyBaseMapper

  1. package cn.itcast.mp.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import java.util.List;
  4. public interface MyBaseMapper<T> extends BaseMapper<T> {
  5. //扩充的方法
  6. List<T> findAll();
  7. }

8.2.编写MySqlInjector

如果直接继承AbstractSqlInjector的话,那么原有的BaseMapper中的方法将失效,所以这里选择继承DefaultSqlInjector进行扩展。

  1. package cn.itcast.mp.injectors;
  2. import com.baomidou.mybatisplus.core.injector.AbstractMethod;
  3. import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. public class MySqlInjector extends DefaultSqlInjector {
  7. @Override
  8. public List<AbstractMethod> getMethodList() {
  9. List<AbstractMethod> list = new ArrayList<>();
  10. // 获取父类中的集合
  11. list.addAll(super.getMethodList());
  12. // 再扩充自定义的方法
  13. list.add(new FindAll());
  14. return list;
  15. }
  16. }

8.3.编写FindAll

  1. package cn.itcast.mp.injectors;
  2. import com.baomidou.mybatisplus.core.injector.AbstractMethod;
  3. import com.baomidou.mybatisplus.core.metadata.TableInfo;
  4. import org.apache.ibatis.mapping.MappedStatement;
  5. import org.apache.ibatis.mapping.SqlSource;
  6. public class FindAll extends AbstractMethod {
  7. @Override
  8. public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
  9. String sql = "select * from " + tableInfo.getTableName();
  10. SqlSource sqlSource = languageDriver.createSqlSource(configuration,sql, modelClass);
  11. return this.addSelectMappedStatement(mapperClass, "findAll", sqlSource, modelClass, tableInfo);
  12. }
  13. }

8.4.注册到Spring容器中

在SpringBoot的自定义的配置类中配置MySqlInjector(即将MySqlInjector注册到Spring容器中)

  1. /** * 注入自定义的SQL注入器 * @return */
  2. @Bean
  3. public MySqlInjector mySqlInjector(){
  4. return new MySqlInjector();
  5. }

8.5.编写测试方法

如果继续使用userMapper来进行测试,那么要将其继承的接口改为自定义的MyBaseMapper。

  1. package cn.itcast.mp.mapper;
  2. import cn.itcast.mp.pojo.User;
  3. public interface UserMapper extends MyBaseMapper<User> {
  4. }

具体的测试方法如下:

  1. @Test
  2. public void testFindAll(){
  3. List<User> users = this.userMapper.findAll();
  4. for (User user : users) {
  5. System.out.println(user);
  6. }
  7. }

结果如下:

9.自动填充功能

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

9.1.添加@TableField注解

例如,为User类中的password添加自动填充功能,在新增数据时有效。

  1. //插入数据时进行填充
  2. @TableField(fill = FieldFill.INSERT)
  3. private String password;

此外,FieldFill提供了以下多种模式选择:

  1. package com.baomidou.mybatisplus.annotation;
  2. /** * 字段填充策略枚举类 * * <p> * 判断注入的 insert 和 update 的 sql 脚本是否在对应情况下忽略掉字段的 if 标签生成 * <if test="...">......</if> * 判断优先级比 {@link FieldStrategy} 高 * </p> * * @author hubin * @since 2017-06-27 */
  3. public enum FieldFill {
  4. /** * 默认不处理 */
  5. DEFAULT,
  6. /** * 插入时填充字段 */
  7. INSERT,
  8. /** * 更新时填充字段 */
  9. UPDATE,
  10. /** * 插入和更新时填充字段 */
  11. INSERT_UPDATE
  12. }

9.2.编写MyMetaObjectHandler

  1. package cn.itcast.mp.handler;
  2. import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
  3. import org.apache.ibatis.reflection.MetaObject;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class MyMetaObjectHandler implements MetaObjectHandler {
  7. /** * 插入数据时填充 * @param metaObject */
  8. @Override
  9. public void insertFill(MetaObject metaObject) {
  10. // 先获取到password的值,再进行判断,如果为空,就进行填充,如果不为空,就不做处理
  11. Object password = getFieldValByName("password", metaObject);
  12. if(null == password){
  13. setFieldValByName("password", "888888", metaObject);
  14. }
  15. }
  16. /** * 更新数据时填充 * @param metaObject */
  17. @Override
  18. public void updateFill(MetaObject metaObject) {
  19. }
  20. }

9.3.编写测试用例

  1. @Test
  2. public void testInsert() {
  3. User user = new User();
  4. user.setUserName("xiaoli");
  5. //不设置密码
  6. user.setName("小李");
  7. user.setAge(21);
  8. user.setEmail("xiaoli@itcast.com");
  9. //result:数据库受影响的行数
  10. int result = this.userMapper.insert(user);
  11. System.out.println("result => " + result);
  12. //获取自增长后的id值, 自增长后的id值会回填到user对象中
  13. System.out.println("id => " + user.getId());
  14. }

10.逻辑删除

开发系统时,有时候在实现功能时,删除操作需要实现逻辑删除,所谓逻辑删除就是将数据标记为删除,而并非真正的物理删除(非DELETE操作),查询时需要携带状态条件,确保被标记的数据不被查询到。这样做的目的就是避免数据被真正的删除。MP就提供了这样的功能,下面将展开介绍。

10.1.修改表结构

为tb_user表增加deleted字段,用于表示数据是否被删除,1代表删除,0代表未删除。

  1. ALTER TABLE `tb_user`
  2. ADD COLUMN `deleted` int(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除'
  3. AFTER `version`;

同时,也修改User实体,增加deleted属性并且添加@TableLogic注解

  1. @TableLogic
  2. private Integer deleted;

10.2.在application.properties中进行配置

  1. # 删除状态的值为:1
  2. mybatis-plus.global-config.db-config.logic-delete-value=1
  3. # 未删除状态的值为:0
  4. mybatis-plus.global-config.db-config.logic-not-delete-value=0

10.3.编写测试方法

  1. @Test
  2. public void testDeleteById(){
  3. // 根据id删除数据(逻辑删除)
  4. int result = this.userMapper.deleteById(2L);
  5. System.out.println("result => " + result);
  6. }

当id为2的用户被进行了逻辑删除后,再次查找该用户时则找不到

  1. @Test
  2. public void testSelectById() {
  3. //根据id查询数据
  4. User user = this.userMapper.selectById(2L);
  5. System.out.println("result = " + user);
  6. }

11.通用枚举

解决了繁琐的配置,让MyBatis更加方便地使用枚举属性!

11.1.修改表结构

为tb_user表增加sex字段,用于表示用户地性别,1代表男,0代表女。

  1. ALTER TABLE `tb_user`
  2. ADD COLUMN `sex` int(1) NULL DEFAULT 1 COMMENT '1-男,2-女'
  3. AFTER `deleted`;

11.2.定义枚举

  1. package cn.itcast.mp.enums;
  2. import com.baomidou.mybatisplus.core.enums.IEnum;
  3. public enum SexEnum implements IEnum<Integer> {
  4. MAN(1,"男"),
  5. WOMAN(2,"女");
  6. private int value;
  7. private String desc;
  8. SexEnum(int value, String desc) {
  9. this.value = value;
  10. this.desc = desc;
  11. }
  12. @Override
  13. public Integer getValue() {
  14. return this.value;
  15. }
  16. @Override
  17. public String toString() {
  18. return this.desc;
  19. }
  20. }

11.3.在application.properties中进行配置

  1. # 枚举包扫描
  2. mybatis-plus.type-enums-package=cn.itcast.mp.enums

11.4.修改实体类User

在User实体类中添加SexEnum字段

  1. //性别,枚举类型
  2. private SexEnum sex;

11.5.编写测试方法

(1)添加测试

  1. @Test
  2. public void testEnum(){
  3. User user = new User();
  4. user.setUserName("xiaofang");
  5. user.setPassword("123456");
  6. user.setAge(20);
  7. user.setName("小芳");
  8. user.setEmail("xiaofang@itcast.cn");
  9. user.setVersion(1);
  10. user.setSex(SexEnum.WOMAN); //使用的是枚举
  11. // 调用AR的insert方法进行插入数据
  12. boolean insert = user.insert();
  13. System.out.println("result => " + insert);
  14. }

(2)条件查询测试

  1. @Test
  2. public void testSelectBySex(){
  3. QueryWrapper<User> wrapper = new QueryWrapper<>();
  4. wrapper.ge("sex", SexEnum.WOMAN)
  5. .or()
  6. .eq("age", 21)
  7. .select("id","name","age"); //指定查询的字段
  8. List<User> users = this.userMapper.selectList(wrapper);
  9. for (User user : users) {
  10. System.out.println(user);
  11. }
  12. }

12.代码生成器

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

12.1.创建工程

创建一个名为itcast-mp-generator的Maven工程

12.2.在pom.xml中导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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">
  3. <modelVersion>4.0.0</modelVersion>
  4. <parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.4.RELEASE</version>
  8. </parent>
  9. <groupId>cn.itcast.mp</groupId>
  10. <artifactId>itcast-mp-generator</artifactId>
  11. <version>1.0-SNAPSHOT</version>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-test</artifactId>
  16. <scope>test</scope>
  17. </dependency>
  18. <!--mybatis-plus的springboot支持-->
  19. <dependency>
  20. <groupId>com.baomidou</groupId>
  21. <artifactId>mybatis-plus-boot-starter</artifactId>
  22. <version>3.1.1</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.baomidou</groupId>
  26. <artifactId>mybatis-plus-generator</artifactId>
  27. <version>3.1.1</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-freemarker</artifactId>
  32. </dependency>
  33. <!--mysql驱动-->
  34. <dependency>
  35. <groupId>mysql</groupId>
  36. <artifactId>mysql-connector-java</artifactId>
  37. <version>5.1.47</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.slf4j</groupId>
  41. <artifactId>slf4j-log4j12</artifactId>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.projectlombok</groupId>
  45. <artifactId>lombok</artifactId>
  46. <optional>true</optional>
  47. </dependency>
  48. </dependencies>
  49. <build>
  50. <plugins>
  51. <plugin>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-maven-plugin</artifactId>
  54. </plugin>
  55. </plugins>
  56. </build>
  57. </project>

12.3.生成器代码

  1. package cn.itcast.mp.generator;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Scanner;
  5. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
  6. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  7. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  8. import com.baomidou.mybatisplus.generator.AutoGenerator;
  9. import com.baomidou.mybatisplus.generator.InjectionConfig;
  10. import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
  11. import com.baomidou.mybatisplus.generator.config.FileOutConfig;
  12. import com.baomidou.mybatisplus.generator.config.GlobalConfig;
  13. import com.baomidou.mybatisplus.generator.config.PackageConfig;
  14. import com.baomidou.mybatisplus.generator.config.StrategyConfig;
  15. import com.baomidou.mybatisplus.generator.config.TemplateConfig;
  16. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  17. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  18. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  19. /** * <p> * mysql 代码生成器演示例子 * </p> */
  20. public class MysqlGenerator {
  21. /** * <p> * 读取控制台内容 * </p> */
  22. public static String scanner(String tip) {
  23. Scanner scanner = new Scanner(System.in);
  24. StringBuilder help = new StringBuilder();
  25. help.append("请输入" + tip + ":");
  26. System.out.println(help.toString());
  27. if (scanner.hasNext()) {
  28. String ipt = scanner.next();
  29. if (StringUtils.isNotEmpty(ipt)) {
  30. return ipt;
  31. }
  32. }
  33. throw new MybatisPlusException("请输入正确的" + tip + "!");
  34. }
  35. /** * RUN THIS */
  36. public static void main(String[] args) {
  37. // 代码生成器
  38. AutoGenerator mpg = new AutoGenerator();
  39. // 全局配置
  40. GlobalConfig gc = new GlobalConfig();
  41. String projectPath = System.getProperty("user.dir");
  42. gc.setOutputDir(projectPath + "/src/main/java");
  43. gc.setAuthor("itcast");
  44. gc.setOpen(false);
  45. mpg.setGlobalConfig(gc);
  46. // 数据源配置
  47. DataSourceConfig dsc = new DataSourceConfig();
  48. dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8");
  49. // dsc.setSchemaName("public");
  50. dsc.setDriverName("com.mysql.jdbc.Driver");
  51. dsc.setUsername("root");
  52. dsc.setPassword("123456");
  53. mpg.setDataSource(dsc);
  54. // 包配置
  55. PackageConfig pc = new PackageConfig();
  56. pc.setModuleName(scanner("模块名"));
  57. pc.setParent("cn.itcast.mp.generator");
  58. mpg.setPackageInfo(pc);
  59. // 自定义配置
  60. InjectionConfig cfg = new InjectionConfig() {
  61. @Override
  62. public void initMap() {
  63. // to do nothing
  64. }
  65. };
  66. List<FileOutConfig> focList = new ArrayList<>();
  67. focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
  68. @Override
  69. public String outputFile(TableInfo tableInfo) {
  70. // 自定义输入文件名称
  71. return projectPath + "/itcast-mp-generator/src/main/resources/mapper/" + pc.getModuleName()
  72. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  73. }
  74. });
  75. cfg.setFileOutConfigList(focList);
  76. mpg.setCfg(cfg);
  77. mpg.setTemplate(new TemplateConfig().setXml(null));
  78. // 策略配置
  79. StrategyConfig strategy = new StrategyConfig();
  80. strategy.setNaming(NamingStrategy.underline_to_camel);
  81. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  82. // strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity");
  83. strategy.setEntityLombokModel(true);
  84. // strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController");
  85. strategy.setInclude(scanner("表名"));
  86. strategy.setSuperEntityColumns("id");
  87. strategy.setControllerMappingHyphenStyle(true);
  88. strategy.setTablePrefix(pc.getModuleName() + "_");
  89. mpg.setStrategy(strategy);
  90. // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
  91. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  92. mpg.execute();
  93. }
  94. }

运行上述的main方法即可自动生成代码。

13.MybatisX——快速开发插件

MybatisX 是一款基于 IDEA 的快速开发插件,其目的在于提高开发效率。

13.1.安装方法

打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入mybatisx 搜索并安装,安装之后重启IDEA即可使用该插件。

13.2.功能

(1)Java 与 XML 调回跳转;

(2)Mapper 方法自动生成 XML;

相关文章

目录