MyBatis-Plus系列(一)--MyBatis-Plus集成Druid环境搭建

2,410 阅读32分钟
原文链接: blog.csdn.net

一、简介


Mybatis-Plus是一款 MyBatis 动态 sql 自动注入 crud 简化 增 删 改 查 操作中间件。启动加载 XML 配置时注入 mybatis 单表 动态 SQL 操作 ,为简化开发工作、提高生产率而生。Mybatis-Plus 启动注入非拦截实现、性能更优。


1.1、原理


1.2、特性

  • 无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变,引入 Mybatis-Plus 不会对您现有的 Mybatis 构架产生任何影响,而且 MP 支持所有 Mybatis 原生的特性
  • 依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring
  • 损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作
  • 预防Sql注入:内置Sql注入剥离器,有效预防Sql注入攻击
  • 通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题
  • 支持热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
  • 支持ActiveRecord:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作
  • 支持代码生成:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(P.S. 比 Mybatis 官方的 Generator 更加强大!)
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持关键词自动转义:支持数据库关键词(order、key......)自动转义,还可自定义关键词
  • 内置分页插件:基于Mybatis物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通List查询
  • 内置性能分析插件:可输出Sql语句以及其执行时间,建议开发测试时启用该功能,能有效解决慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,预防误操作


1.3、简化


MP简化了MyBatis的单表基本操作,提供了两种操作方式:

(1)、传统模式

Mybatis-Plus 通过 EntityWrapper(简称 EW,MP 封装的一个查询条件构造器)或者 Condition(与EW类似) 来让用户自由的构建查询条件,简单便捷,没有额外的负担,能够有效提高开发效率。

(2)、ActiveRecord模式

Active Record(简称AR)模式是软件里的一种架构性模式,主要概念是关系型数据库中的数据在内存中以对象的形式存储。由Martin Fowler在其2003年初版的书籍《Patterns of Enterprise Application Architecture》命名。遵循该模式的对象接口一般包括如Insert, Update, 和 Delete这样的函数,以及对应于底层数据库表字段的相关属性。

AR模式是一种访问数据库数据的方式。数据表或视图被映射成一个类。每个对象实例则对应于表的一条记录。对象被创建后,通过save就可以向表中新添一行记录。当对象被更新时,表中相应记录也被更新。这个包裹类通过属性或方法的形式实现访问表或视图中的每一个字段。

该模式主要被对象持久化工具采用,用于对象关系映射 (ORM). 典型的,外键关系会以合适的对象实例属性的形式暴露访问。


1.4、常用实体注解

1.表名注解@TableName
2.主键注解@TableId
3.字段注解@TableFieId
4.序列主键策略注解@KeySequence


二、搭建


环境:


IDEA

Spring Boot-2.0

MyBatis-Plus-2.2.0

MyBatisPlus-spring-boot-starter-1.0.5

druid-spring-boot-starter-1.1.9


首先创建SpringBoot Maven项目,然后加入以下依赖:

[html] view plain copy print?
  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"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >  
  4.     <modelVersion>4.0.0</modelVersion >  
  5.   
  6.     <groupId>com.fendo.mybatis.plus</groupId >  
  7.     <artifactId>demo</artifactId >  
  8.     <version>0.0.1-SNAPSHOT</version >  
  9.     <packaging>jar</packaging >  
  10.   
  11.     <name>mybatis-plus</name >  
  12.     <description>mybatis-plus 示例</description >  
  13.   
  14.     <parent>  
  15.         <groupId>org.springframework.boot</ groupId>  
  16.         <artifactId>spring-boot-starter-parent</ artifactId>  
  17.         <version>2.0.0.RELEASE</ version>  
  18.         <relativePath/>   
  19.     </parent>  
  20.   
  21.     <properties>  
  22.         <project.build.sourceEncoding>UTF-8</ project.build.sourceEncoding>  
  23.         <project.reporting.outputEncoding>UTF-8</ project.reporting.outputEncoding>  
  24.         <java.version>1.8</ java.version>  
  25.         <maven.compiler.source>1.8</ maven.compiler.source>  
  26.         <maven.compiler.target>1.8</ maven.compiler.target>  
  27.         <mybatisplus-spring-boot-starter.version>1.0.5 </mybatisplus-spring-boot-starter.version>  
  28.         <mybatisplus.version>2.2.0</ mybatisplus.version>  
  29.         <fastjson.version>1.2.39</ fastjson.version>  
  30.     </properties>  
  31.   
  32.     <dependencies>  
  33.         <dependency>  
  34.             <groupId>org.springframework.boot </groupId>  
  35.             <artifactId>spring-boot-starter-web </artifactId>  
  36.         </dependency>  
  37.         <dependency>  
  38.             <groupId>org.springframework.boot </groupId>  
  39.             <artifactId>spring-boot-starter-jetty </artifactId>  
  40.         </dependency>  
  41.         <dependency>  
  42.             <groupId>org.springframework.boot </groupId>  
  43.             <artifactId>spring-boot-devtools </artifactId>  
  44.             <scope>runtime</ scope>  
  45.         </dependency>  
  46.         <dependency>  
  47.             <groupId>mysql</ groupId>  
  48.             <artifactId>mysql-connector-java </artifactId>  
  49.             <scope>runtime</ scope>  
  50.         </dependency>  
  51.         <dependency>  
  52.             <groupId>org.springframework.boot </groupId>  
  53.             <artifactId>spring-boot-starter-test </artifactId>  
  54.             <scope>test</ scope>  
  55.         </dependency>  
  56.   
  57.         <!-- mybatis-plus begin -->  
  58.         <dependency>  
  59.             <groupId>com.baomidou </groupId>  
  60.             <artifactId>mybatisplus-spring-boot-starter </artifactId>  
  61.             <version>${mybatisplus-spring-boot-starter.version} </version>  
  62.         </dependency>  
  63.         <dependency>  
  64.             <groupId>com.baomidou </groupId>  
  65.             <artifactId>mybatis-plus </artifactId>  
  66.             <version>${mybatisplus.version} </version>  
  67.         </dependency>  
  68.         <!-- mybatis-plus end -->  
  69.         <dependency>  
  70.             <groupId>com.alibaba </groupId>  
  71.             <artifactId>fastjson </artifactId>  
  72.             <version>${fastjson.version} </version>  
  73.         </dependency>  
  74.         <dependency>  
  75.             <groupId>com.alibaba </groupId>  
  76.             <artifactId>druid-spring-boot-starter </artifactId>  
  77.             <version>1.1.9</ version>  
  78.         </dependency>  
  79.         <dependency>  
  80.             <groupId>com.jayway.restassured </groupId>  
  81.             <artifactId>rest-assured </artifactId>  
  82.             <version>2.9.0</ version>  
  83.         </dependency>  
  84.         <!--Swagger UI-->  
  85.         <dependency>  
  86.             <groupId>io.springfox </groupId>  
  87.             <artifactId>springfox-swagger2 </artifactId>  
  88.             <version>2.2.2</ version>  
  89.         </dependency>  
  90.         <dependency>  
  91.             <groupId>io.springfox </groupId>  
  92.             <artifactId>springfox-swagger-ui </artifactId>  
  93.             <version>2.2.2</ version>  
  94.         </dependency>  
  95.     </dependencies>  
  96.   
  97.     <build>  
  98.         <plugins>  
  99.             <plugin>  
  100.                 <groupId>org.springframework.boot </groupId>  
  101.                 <artifactId>spring-boot-maven-plugin </artifactId>  
  102.             </plugin>  
  103.         </plugins>  
  104.     </build>  
  105.   
  106.   
  107. </project>  
<?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.fendo.mybatis.plus</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mybatis-plus</name>
	<description>mybatis-plus 示例</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath/> 
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<mybatisplus-spring-boot-starter.version>1.0.5</mybatisplus-spring-boot-starter.version>
		<mybatisplus.version>2.2.0</mybatisplus.version>
		<fastjson.version>1.2.39</fastjson.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- mybatis-plus begin -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatisplus-spring-boot-starter</artifactId>
			<version>${mybatisplus-spring-boot-starter.version}</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus</artifactId>
			<version>${mybatisplus.version}</version>
		</dependency>
		<!-- mybatis-plus end -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
		<dependency>
			<groupId>com.jayway.restassured</groupId>
			<artifactId>rest-assured</artifactId>
			<version>2.9.0</version>
		</dependency>
		<!--Swagger UI-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

然后新建application.yml配置文件

[html] view plain copy print?
  1. # Tomcat  
  2. server:  
  3.     tomcat:  
  4.         uri-encoding: UTF-8  
  5.         max-threads: 1000  
  6.         min-spare-threads: 30  
  7.     port: 8080  
  8.     connection-timeout: 5000  
  9. #datasource  
  10. spring:  
  11.     datasource:  
  12.         name: fendo  
  13.         url: jdbc:mysql://localhost:3306/fendo_plus_boot?useUnicode=true& characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true& useLegacyDatetimeCode=false&serverTimezone=UTC& useSSL=false  
  14.         username: root  
  15.         password: root  
  16.         type: com.alibaba.druid.pool.DruidDataSource  
  17.         driver-class-name: com.mysql.jdbc.Driver  
  18.         initialSize: 5  
  19.         minIdle: 5  
  20.         maxActive: 20  
  21.         maxWait: 60000  
  22.         timeBetweenEvictionRunsMillis: 60000  
  23.         minEvictableIdleTimeMillis: 300000  
  24.         validationQuery: SELECT 1 FROM DUAL  
  25.         testWhileIdle: true  
  26.         testOnBorrow: false  
  27.         testOnReturn: false  
  28.         poolPreparedStatements: true  
  29.         maxPoolPreparedStatementPerConnectionSize: 20  
  30.         spring.datasource.filters: stat,wall,log4j  
  31.         connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=5000  
  32.     # jackson时间格式化  
  33.     jackson:  
  34.         time-zone: GMT+8  
  35.         date-format: yyyy-MM-dd HH:mm:ss  
  36.     thymeleaf:  
  37.        cache: false  
  38.        prefix: classpath:/templates/  
  39.        suffix: .html  
  40.        mode: LEGACYHTML5  
  41.        encoding: UTF-8  
  42.        check-template: false  
  43.        enabled: false  
  44.     resources: # 指定静态资源的路径  
  45.        static-locations: classpath:/static/,classpath:/views/  
  46.     mvc:  
  47.       view:  
  48.         prefix: /WEB-INF/  
  49.         suffix: .jsp  
  50. # Mybatis-Plus 配置  
  51. mybatis-plus:  
  52.   mapper-locations: classpath:/mapper/*Mapper.xml  
  53.   typeAliasesPackage: com.fendo.mybatis.plus.entity  
  54.   typeEnumsPackage: com.fendo.mybatis.plus.entity.enums  
  55. #  global-config:  
  56. #    id-type: 2  
  57. #    field-strategy: 2  
  58. #    db-column-underline: true  
  59. #    refresh-mapper: true  
  60. #    #capital-mode: true  
  61. #    #key-generator: com.baomidou.springboot.xxx  
  62. #    logic-delete-value: 0  
  63. #    logic-not-delete-value: 1  
  64. #    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector  
  65. #    #meta-object-handler: com.baomidou.springboot.xxx  
  66. #    #sql-injector: com.baomidou.springboot.xxx  
  67. #  configuration:  
  68. #    map-underscore-to-camel-case: true  
  69. #    cache-enabled: false  
  70.   global-config:  
  71.     id-type: 3  #0:数据库ID自增   1:用户输入id  2:全局唯一id(IdWorker)  3:全局唯一ID(uuid)  
  72.     db-column-underline: false  
  73.     refresh-mapper: true  
  74.   configuration:  
  75.     map-underscore-to-camel-case: true  
  76.     cache-enabled: true #配置的缓存的全局开关  
  77.     lazyLoadingEnabled: true #延时加载的开关  
  78.     multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性  
  79.     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用  
# Tomcat
server:
    tomcat:
        uri-encoding: UTF-8
        max-threads: 1000
        min-spare-threads: 30
    port: 8080
    connection-timeout: 5000
#datasource
spring:
    datasource:
        name: fendo
        url: jdbc:mysql://localhost:3306/fendo_plus_boot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
        username: root
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        spring.datasource.filters: stat,wall,log4j
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # jackson时间格式化
    jackson:
        time-zone: GMT+8
        date-format: yyyy-MM-dd HH:mm:ss
    thymeleaf:
       cache: false
       prefix: classpath:/templates/
       suffix: .html
       mode: LEGACYHTML5
       encoding: UTF-8
       check-template: false
       enabled: false
    resources: # 指定静态资源的路径
       static-locations: classpath:/static/,classpath:/views/
    mvc:
      view:
        prefix: /WEB-INF/
        suffix: .jsp
# Mybatis-Plus 配置
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  typeAliasesPackage: com.fendo.mybatis.plus.entity
  typeEnumsPackage: com.fendo.mybatis.plus.entity.enums
#  global-config:
#    id-type: 2
#    field-strategy: 2
#    db-column-underline: true
#    refresh-mapper: true
#    #capital-mode: true
#    #key-generator: com.baomidou.springboot.xxx
#    logic-delete-value: 0
#    logic-not-delete-value: 1
#    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#    #meta-object-handler: com.baomidou.springboot.xxx
#    #sql-injector: com.baomidou.springboot.xxx
#  configuration:
#    map-underscore-to-camel-case: true
#    cache-enabled: false
  global-config:
    id-type: 3  #0:数据库ID自增   1:用户输入id  2:全局唯一id(IdWorker)  3:全局唯一ID(uuid)
    db-column-underline: false
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: true #配置的缓存的全局开关
    lazyLoadingEnabled: true #延时加载的开关
    multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用


创建MyBatis-Plus配置类MybatisPlusConfig

[html] view plain copy print?
  1. /**  
  2.  * projectName: fendo-plus-boot  
  3.  * fileName: MybatisPlusConfig.java  
  4.  * packageName: com.fendo.mybatis.plus.config  
  5.  * date: 2018-01-12 23:13  
  6.  * copyright(c) 2017-2020 xxx公司  
  7.  */  
  8. package com.fendo.mybatis.plus.config;  
  9.   
  10. import com.baomidou.mybatisplus.plugins.PaginationInterceptor;  
  11. import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;  
  12. import org.mybatis.spring.annotation.MapperScan;  
  13. import org.springframework.context.annotation.Bean;  
  14. import org.springframework.context.annotation.Configuration;  
  15.   
  16. /**  
  17.  * @version: V1.0  
  18.  * @author: fendo  
  19.  * @className: MybatisPlusConfig  
  20.  * @packageName: com.fendo.mybatis.plus.config  
  21.  * @description: Mybatis-plus配置类  
  22.  * @data: 2018-01-12 23:13  
  23.  **/  
  24. @Configuration  
  25. @MapperScan("com.fendo.mybatis.plus.mapper*")  
  26. public class MybatisPlusConfig {  
  27.     /**  
  28.      * mybatis-plus SQL执行效率插件【生产环境可以关闭】  
  29.      */  
  30.     @Bean  
  31.     public PerformanceInterceptor performanceInterceptor() {  
  32.         return new PerformanceInterceptor();  
  33.     }  
  34.   
  35.     /**  
  36.      * 分页插件  
  37.      */  
  38.     @Bean  
  39.     public PaginationInterceptor paginationInterceptor() {  
  40.         return new PaginationInterceptor();  
  41.     }  
  42. }  
/**
 * projectName: fendo-plus-boot
 * fileName: MybatisPlusConfig.java
 * packageName: com.fendo.mybatis.plus.config
 * date: 2018-01-12 23:13
 * copyright(c) 2017-2020 xxx公司
 */
package com.fendo.mybatis.plus.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @version: V1.0
 * @author: fendo
 * @className: MybatisPlusConfig
 * @packageName: com.fendo.mybatis.plus.config
 * @description: Mybatis-plus配置类
 * @data: 2018-01-12 23:13
 **/
@Configuration
@MapperScan("com.fendo.mybatis.plus.mapper*")
public class MybatisPlusConfig {
    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

三、测试


首先创建User表

[html] view plain copy print?
  1. CREATE TABLE `user` (  
  2.   `id` varchar(32) NOT NULL,  
  3.   `name` varchar(255) DEFAULT NULL,  
  4.   `age` int(2) DEFAULT NULL,  
  5.   `sex` int(2) DEFAULT NULL,  
  6.   `create_by` varchar(255) DEFAULT NULL,  
  7.   `create_date` datetime DEFAULT NULL,  
  8.   `update_by` varchar(255) DEFAULT NULL,  
  9.   `update_date` datetime DEFAULT NULL,  
  10.   `remarks` varchar(255) DEFAULT NULL,  
  11.   `del_flag` varchar(255) DEFAULT NULL,  
  12.   PRIMARY KEY (`id`)  
  13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
CREATE TABLE `user` (
  `id` varchar(32) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(2) DEFAULT NULL,
  `sex` int(2) DEFAULT NULL,
  `create_by` varchar(255) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  `update_by` varchar(255) DEFAULT NULL,
  `update_date` datetime DEFAULT NULL,
  `remarks` varchar(255) DEFAULT NULL,
  `del_flag` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

然后创建controller,entity,service,mapper,项目结构如下所示:



Controller测试类如下:

[html] view plain copy print?
  1. /**  
  2.  * projectName: mybatis-plus  
  3.  * fileName: UserController.java  
  4.  * packageName: com.fendo.mybatis.plus.controller  
  5.  * date: 2018-03-24 19:07  
  6.  * copyright(c) 2017-2020 xxx公司  
  7.  */  
  8. package com.fendo.mybatis.plus.controller;  
  9.   
  10. import com.alibaba.fastjson.JSONObject;  
  11. import com.baomidou.mybatisplus.mapper.EntityWrapper;  
  12. import com.baomidou.mybatisplus.plugins.Page;  
  13. import com.baomidou.mybatisplus.plugins.pagination.PageHelper;  
  14. import com.fendo.mybatis.plus.common.utils.IdGen;  
  15. import com.fendo.mybatis.plus.entity.UserEntity;  
  16. import com.fendo.mybatis.plus.entity.enums.AgeEnum;  
  17. import com.fendo.mybatis.plus.entity.enums.SexEnum;  
  18. import com.fendo.mybatis.plus.service.UserService;  
  19. import io.swagger.annotations.Api;  
  20. import io.swagger.annotations.ApiOperation;  
  21. import io.swagger.annotations.ApiResponse;  
  22. import org.springframework.beans.factory.annotation.Autowired;  
  23. import org.springframework.transaction.annotation.Transactional;  
  24. import org.springframework.web.bind.annotation.GetMapping;  
  25. import org.springframework.web.bind.annotation.RequestMapping;  
  26. import org.springframework.web.bind.annotation.RestController;  
  27.   
  28. /**  
  29.  * @version: V1.0  
  30.  * @author: fendo  
  31.  * @className: UserController  
  32.  * @packageName: com.fendo.mybatis.plus.controller  
  33.  * @description: 用户Controller  
  34.  * @data: 2018-03-24 19:07  
  35.  **/  
  36. @RestController  
  37. @RequestMapping("/user")  
  38. @Api("用户操作接口")  
  39. public class UserController {  
  40.   
  41.     @Autowired  
  42.     private UserService userService;  
  43.   
  44.     /**  
  45.      * 分页 PAGE  
  46.      */  
  47.     @GetMapping("/page")  
  48.     @ApiOperation(value = "用户分页数据", response =  UserEntity.class)  
  49.     @ApiResponse(code = 200, message =  "success")  
  50.     public Page<UserEntity> test() {  
  51.         return userService.selectPage(new Page<UserEntity>(0,12));  
  52.     }  
  53.   
  54.     /**  
  55.      * AR 部分测试  
  56.      */  
  57.     @GetMapping("/insert")  
  58.     public Page<UserEntity> insert() {  
  59.         UserEntity user = new UserEntity(IdGen.getUUID(), "testAr", AgeEnum.ONE, SexEnum.FEMALE);  
  60.         System.err.println("删除所有:" + user.delete(null));  
  61.         user.insert();  
  62.         System.err.println("查询插入结果:" + user.selectById().toString());  
  63.         user.setName("mybatis-plus-ar");  
  64.         System.err.println("更新:" + user.updateById());  
  65.         return user.selectPage(new Page<UserEntity>(0, 12), null);  
  66.     }  
  67.   
  68.     /**  
  69.      * 增删改查 CRUD  
  70.      */  
  71.     @GetMapping("/crud")  
  72.     public UserEntity crud() {  
  73.         System.err.println("删除一条数据:" + userService.deleteById("85349feb19f04fa78a7a717f4dce031f"));  
  74.         System.err.println("deleteAll:" + userService.deleteAll());  
  75.         String IdGens = IdGen.getUUID();  
  76.         System.err.println("插入一条数据:" + userService.insert(new UserEntity(IdGens, "张三", AgeEnum.TWO, SexEnum.FEMALE)));  
  77.         UserEntity user = new UserEntity("张三", AgeEnum.TWO, SexEnum.MALE);  
  78.         boolean result = userService.insert(user);  
  79.   
  80.         // 自动回写的ID  
  81.         String id = user.getId();  
  82.         System.err.println("插入一条数据:" + result + ", 插入信息:" + user.toString());  
  83.         System.err.println("查询:" + userService.selectById(id).toString());  
  84.         System.err.println("更新一条数据:" + userService.updateById(new UserEntity(IdGens, "三毛", AgeEnum.ONE, SexEnum.FEMALE)));  
  85.         for (int i = 0; i  < 5; ++i) {  
  86.             userService.insert(new UserEntity( IdGen.getUUID(), "张三" + i, AgeEnum.ONE, SexEnum.FEMALE));  
  87.         }  
  88.         Page<UserEntity> userListPage =  userService.selectPage(new Page<UserEntity>(1, 5), new EntityWrapper <>(new UserEntity()));  
  89.         System.err.println("total=" + userListPage.getTotal() + ", current list  size=" + userListPage.getRecords().size());  
  90.         return userService.selectById(IdGens);  
  91.     }  
  92.   
  93.     /**  
  94.      * 插入 OR 修改  
  95.      */  
  96.     @GetMapping("/save")  
  97.     public UserEntity save() {  
  98.         String IdGens = IdGen.getUUID();  
  99.         UserEntity user = new UserEntity(IdGens, "王五", AgeEnum.ONE, SexEnum.FEMALE);  
  100.         userService.insertOrUpdate(user);  
  101.         return userService.selectById(IdGens);  
  102.     }  
  103.   
  104.     @GetMapping("/add")  
  105.     public Object addUser() {  
  106.         UserEntity user = new UserEntity(IdGen.getUUID(), "张三'特殊`符号", AgeEnum.TWO, SexEnum.FEMALE);  
  107.         JSONObject result = new JSONObject();  
  108.         result.put("result", userService.insert(user));  
  109.         return result;  
  110.     }  
  111.   
  112.     @GetMapping("/selectsql")  
  113.     public Object getUserBySql() {  
  114.         JSONObject result = new JSONObject();  
  115.         result.put("records", userService.selectListBySQL());  
  116.         return result;  
  117.     }  
  118.   
  119.     /**  
  120.      * 7、分页 size 一页显示数量  current 当前页码  
  121.      * 方式一:http://localhost:8080/user/page?size=1¤t= 1  
  122.      * 方式二:http://localhost:8080/user/pagehelper?size=1¤ t=1  
  123.      */  
  124.   
  125.     // 参数模式分页  
  126.     @GetMapping("/pages")  
  127.     public Object page(Page page) {  
  128.         return userService.selectPage(page);  
  129.     }  
  130.   
  131.     // ThreadLocal 模式分页  
  132.     @GetMapping("/pagehelper")  
  133.     public Object pagehelper(Page page) {  
  134.         PageHelper.setPagination(page);  
  135.         page.setRecords(userService.selectList(null));  
  136.         page.setTotal(PageHelper.freeTotal());//获取总数并释放资源 也可以 PageHelper.getTotal()  
  137.         return page;  
  138.     }  
  139.   
  140.   
  141.     /**  
  142.      * 测试事物  
  143.      * http://localhost:8080/user/test_transactional<br>  
  144.      * 访问如下并未发现插入数据说明事物可靠!!<br>  
  145.      * http://localhost:8080/user/test<br>  
  146.      * <br>  
  147.      * 启动  Application 加上 @EnableTransactionManagement 注解其实可无默认貌似就开启了<br >  
  148.      * 需要事物的方法加上 @Transactional 必须的哦!!  
  149.      */  
  150.     @Transactional  
  151.     @GetMapping("/test_transactional")  
  152.     public void testTransactional() {  
  153.         String IdGens = IdGen.getUUID();  
  154.         userService.insert(new UserEntity(IdGens, "测试事物", AgeEnum.ONE, SexEnum.FEMALE));  
  155.         System.out.println(" 这里手动抛出异常,自动回滚数据 : " + IdGens);  
  156.         throw new RuntimeException();  
  157.     }  
  158.   
  159. }  
/**
 * projectName: mybatis-plus
 * fileName: UserController.java
 * packageName: com.fendo.mybatis.plus.controller
 * date: 2018-03-24 19:07
 * copyright(c) 2017-2020 xxx公司
 */
package com.fendo.mybatis.plus.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.fendo.mybatis.plus.common.utils.IdGen;
import com.fendo.mybatis.plus.entity.UserEntity;
import com.fendo.mybatis.plus.entity.enums.AgeEnum;
import com.fendo.mybatis.plus.entity.enums.SexEnum;
import com.fendo.mybatis.plus.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version: V1.0
 * @author: fendo
 * @className: UserController
 * @packageName: com.fendo.mybatis.plus.controller
 * @description: 用户Controller
 * @data: 2018-03-24 19:07
 **/
@RestController
@RequestMapping("/user")
@Api("用户操作接口")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页 PAGE
     */
    @GetMapping("/page")
    @ApiOperation(value = "用户分页数据", response = UserEntity.class)
    @ApiResponse(code = 200, message = "success")
    public Page<UserEntity> test() {
        return userService.selectPage(new Page<UserEntity>(0,12));
    }

    /**
     * AR 部分测试
     */
    @GetMapping("/insert")
    public Page<UserEntity> insert() {
        UserEntity user = new UserEntity(IdGen.getUUID(), "testAr", AgeEnum.ONE, SexEnum.FEMALE);
        System.err.println("删除所有:" + user.delete(null));
        user.insert();
        System.err.println("查询插入结果:" + user.selectById().toString());
        user.setName("mybatis-plus-ar");
        System.err.println("更新:" + user.updateById());
        return user.selectPage(new Page<UserEntity>(0, 12), null);
    }

    /**
     * 增删改查 CRUD
     */
    @GetMapping("/crud")
    public UserEntity crud() {
        System.err.println("删除一条数据:" + userService.deleteById("85349feb19f04fa78a7a717f4dce031f"));
        System.err.println("deleteAll:" + userService.deleteAll());
        String IdGens = IdGen.getUUID();
        System.err.println("插入一条数据:" + userService.insert(new UserEntity(IdGens, "张三", AgeEnum.TWO, SexEnum.FEMALE)));
        UserEntity user = new UserEntity("张三", AgeEnum.TWO, SexEnum.MALE);
        boolean result = userService.insert(user);

        // 自动回写的ID
        String id = user.getId();
        System.err.println("插入一条数据:" + result + ", 插入信息:" + user.toString());
        System.err.println("查询:" + userService.selectById(id).toString());
        System.err.println("更新一条数据:" + userService.updateById(new UserEntity(IdGens, "三毛", AgeEnum.ONE, SexEnum.FEMALE)));
        for (int i = 0; i < 5; ++i) {
            userService.insert(new UserEntity( IdGen.getUUID(), "张三" + i, AgeEnum.ONE, SexEnum.FEMALE));
        }
        Page<UserEntity> userListPage = userService.selectPage(new Page<UserEntity>(1, 5), new EntityWrapper<>(new UserEntity()));
        System.err.println("total=" + userListPage.getTotal() + ", current list size=" + userListPage.getRecords().size());
        return userService.selectById(IdGens);
    }

    /**
     * 插入 OR 修改
     */
    @GetMapping("/save")
    public UserEntity save() {
        String IdGens = IdGen.getUUID();
        UserEntity user = new UserEntity(IdGens, "王五", AgeEnum.ONE, SexEnum.FEMALE);
        userService.insertOrUpdate(user);
        return userService.selectById(IdGens);
    }

    @GetMapping("/add")
    public Object addUser() {
        UserEntity user = new UserEntity(IdGen.getUUID(), "张三'特殊`符号", AgeEnum.TWO, SexEnum.FEMALE);
        JSONObject result = new JSONObject();
        result.put("result", userService.insert(user));
        return result;
    }

    @GetMapping("/selectsql")
    public Object getUserBySql() {
        JSONObject result = new JSONObject();
        result.put("records", userService.selectListBySQL());
        return result;
    }

    /**
     * 7、分页 size 一页显示数量  current 当前页码
     * 方式一:http://localhost:8080/user/page?size=1¤t=1
     * 方式二:http://localhost:8080/user/pagehelper?size=1¤t=1
     */

    // 参数模式分页
    @GetMapping("/pages")
    public Object page(Page page) {
        return userService.selectPage(page);
    }

    // ThreadLocal 模式分页
    @GetMapping("/pagehelper")
    public Object pagehelper(Page page) {
        PageHelper.setPagination(page);
        page.setRecords(userService.selectList(null));
        page.setTotal(PageHelper.freeTotal());//获取总数并释放资源 也可以 PageHelper.getTotal()
        return page;
    }


    /**
     * 测试事物
     * http://localhost:8080/user/test_transactional<br>
     * 访问如下并未发现插入数据说明事物可靠!!<br>
     * http://localhost:8080/user/test<br>
     * <br>
     * 启动  Application 加上 @EnableTransactionManagement 注解其实可无默认貌似就开启了<br>
     * 需要事物的方法加上 @Transactional 必须的哦!!
     */
    @Transactional
    @GetMapping("/test_transactional")
    public void testTransactional() {
        String IdGens = IdGen.getUUID();
        userService.insert(new UserEntity(IdGens, "测试事物", AgeEnum.ONE, SexEnum.FEMALE));
        System.out.println(" 这里手动抛出异常,自动回滚数据 : " + IdGens);
        throw new RuntimeException();
    }

}

四、代码生成

创建测试类GeneratorStart

[html] view plain copy print?
  1. /**  
  2.  * projectName: fendo-plus-boot  
  3.  * fileName: GeneratorStart.java  
  4.  * packageName: com.fendo.shiro.generator  
  5.  * date: 2018-01-15 19:59  
  6.  * copyright(c) 2017-2020 xxx公司  
  7.  */  
  8. package com.gzsys.modules.gen;  
  9.   
  10. import com.baomidou.mybatisplus.generator.AutoGenerator;  
  11. import com.baomidou.mybatisplus.generator.InjectionConfig;  
  12. import com.baomidou.mybatisplus.generator.config.*;  
  13. import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;  
  14. import com.baomidou.mybatisplus.generator.config.po.TableInfo;  
  15. import com.baomidou.mybatisplus.generator.config.rules.DbType;  
  16. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;  
  17.   
  18. import java.util.ArrayList;  
  19. import java.util.HashMap;  
  20. import java.util.List;  
  21. import java.util.Map;  
  22.   
  23. /**  
  24.  * @version: V1.0  
  25.  * @author: fendo  
  26.  * @className: GeneratorStart  
  27.  * @packageName: com.gzsys.modules.gen  
  28.  * @description: 代码生成器  
  29.  * @data: 2018-01-15 19:59  
  30.  **/  
  31. public class GeneratorStart {  
  32.   
  33.     public static void main(String[] args) {  
  34.         String packageName = "com.gzsys.modules.yun";  
  35.         boolean serviceNameStartWithI = false;//user - > UserService, 设置成true: user -> IUserService  
  36.         generateByTables(serviceNameStartWithI, packageName, "USER_LOGIN");  
  37.     }  
  38.   
  39.     private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {  
  40.         // 全局配置  
  41.         GlobalConfig config = new GlobalConfig();  
  42.         AutoGenerator mpg = new AutoGenerator();  
  43.         String dbUrl = "jdbc:oracle:thin:@//106.14.160.67:1521/test";  
  44.         DataSourceConfig dataSourceConfig = new DataSourceConfig();  
  45.         dataSourceConfig.setDbType(DbType.ORACLE)  
  46.                 .setUrl(dbUrl)  
  47.                 .setUsername("test")  
  48.                 .setPassword("Eru43wPo")  
  49.                 .setDriverName("oracle.jdbc.driver.OracleDriver");  
  50.         // 策略配置  
  51.         StrategyConfig strategyConfig = new StrategyConfig();  
  52.         strategyConfig  
  53.                 .setCapitalMode(true) // 全局大写命名 ORACLE 注意  
  54.                 .setEntityLombokModel(false) //实体 是否为lombok模型(默认 false)  
  55.                 .setDbColumnUnderline(true) //表名、字段名、是否使用下划线命名  
  56.                 .setNaming(NamingStrategy.underline_to_camel) //表名生成策略  
  57.                 .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组  
  58.         // strategyConfig.setExclude(new String[]{"test"}); // 排除生成的表  
  59.         // 自定义实体父类  
  60.         strategyConfig.setSuperEntityClass("com.gzsys.common.persistence.BaseEntity");  
  61.         // 自定义实体,公共字段  
  62.         strategyConfig.setSuperEntityColumns(new String[] { "ID", "CREATE_TIME", "CREATE_NAME" , "UPDATE_TIME", "UPDATE_NAME", "STATE"});  
  63.         // 自定义 mapper 父类  
  64.         // strategyConfig.setSuperMapperClass("com.baomidou.demo.TestMapper");  
  65.         // 自定义 service 父类  
  66.         //strategyConfig.setSuperServiceClass("com.baomidou.demo.TestService");  
  67.         // 自定义 service 实现类父类  
  68.         //strategyConfig.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");  
  69.         // 自定义 controller 父类  
  70.         strategyConfig.setSuperControllerClass("com.gzsys.common.base.controller.BaseController");  
  71.         // 【实体】是否生成字段常量(默认 false)  
  72.         // public static final String ID = "test_id";  
  73.         // strategyConfig.setEntityColumnConstant(true);  
  74.         // 【实体】是否为构建者模型(默认 false)  
  75.         // public User setName(String name) {this.name = name; return this;}  
  76.         // strategyConfig.setEntityBuliderModel(true);  
  77.   
  78.   
  79.         config.setActiveRecord(true) //是否 开启 ActiveRecord 模式  
  80.                 .setAuthor("fendo")  
  81.                 .setOutputDir("d:\\codeGen")  
  82.                 .setFileOverride(true)  
  83.                 .setActiveRecord(true)  
  84.                 .setEnableCache(false)// XML 二级缓存  
  85.                 .setBaseResultMap(true)// XML ResultMap  
  86.                 .setBaseColumnList(false);// XML columList  
  87.   
  88.         if (!serviceNameStartWithI) {  
  89.             config.setServiceName("%sService"); //自定义Service后戳,注意 %s 会自动填充表实体属性!  
  90.         }  
  91.   
  92.         // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】  
  93.         InjectionConfig cfg = new InjectionConfig() {  
  94.             @Override  
  95.             public void initMap() {  
  96.                 Map<String, Object > map = new HashMap< String, Object>();  
  97.                 map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");  
  98.                 this.setMap(map);  
  99.             }  
  100.         };  
  101.   
  102.   
  103.         // 自定义 xxList.jsp 生成  
  104.         List<FileOutConfig> focList =  new ArrayList<FileOutConfig>();  
  105.         //focList.add(new FileOutConfig("/template/list.jsp.vm") {  
  106.         //    @Override  
  107.         //    public String outputFile(TableInfo tableInfo) {  
  108.         //        // 自定义输入文件名称  
  109.         //        return "D://my_" + tableInfo.getEntityName() + ".jsp";  
  110.         //    }  
  111.         //});  
  112.         //cfg.setFileOutConfigList(focList);  
  113.         //mpg.setCfg(cfg);  
  114.   
  115.         // 调整 xml 生成目录演示  
  116.         focList.add(new FileOutConfig("/templates/mapper.xml.vm") {  
  117.             @Override  
  118.             public String outputFile(TableInfo tableInfo) {  
  119.                 return "d:\\codeGen/resources/mapping/modules/yun/" + tableInfo.getEntityName() + ".xml";  
  120.             }  
  121.         });  
  122.         cfg.setFileOutConfigList(focList);  
  123.         mpg.setCfg(cfg);  
  124.   
  125.         // 关闭默认 xml 生成,调整生成 至 根目录  
  126.         TemplateConfig tc = new TemplateConfig();  
  127.         tc.setXml(null);  
  128.         mpg.setTemplate(tc);  
  129.   
  130.         // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,  
  131.         // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称  
  132.         // TemplateConfig tc = new TemplateConfig();  
  133.         // tc.setController("...");  
  134.         // tc.setEntity("...");  
  135.         // tc.setMapper("...");  
  136.         // tc.setXml("...");  
  137.         // tc.setService("...");  
  138.         // tc.setServiceImpl("...");  
  139.         // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。  
  140.         // mpg.setTemplate(tc);  
  141.   
  142.         //生成文件 配置  
  143.         mpg.setGlobalConfig(config)  //全局 相关配置  
  144.                 .setDataSource(dataSourceConfig) //数据源配置  
  145.                 .setStrategy(strategyConfig) //数据库表配置  
  146.                 .setPackageInfo( //包 相关配置  
  147.                         new PackageConfig()  //跟包相关的配置项  
  148.                                 .setParent(packageName)  //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名  
  149.                                 .setController("controller") //Controller包名  
  150.                                 .setEntity("entity") //entity包名  
  151.                                 //.setXml("/")  
  152.                 )  
  153.                 .execute();  
  154.     }  
  155.   
  156.     private void generateByTables(String packageName, String... tableNames) {  
  157.         generateByTables(true, packageName, tableNames);  
  158.     }  
  159.   
  160. }  
/**
 * projectName: fendo-plus-boot
 * fileName: GeneratorStart.java
 * packageName: com.fendo.shiro.generator
 * date: 2018-01-15 19:59
 * copyright(c) 2017-2020 xxx公司
 */
package com.gzsys.modules.gen;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version: V1.0
 * @author: fendo
 * @className: GeneratorStart
 * @packageName: com.gzsys.modules.gen
 * @description: 代码生成器
 * @data: 2018-01-15 19:59
 **/
public class GeneratorStart {

    public static void main(String[] args) {
        String packageName = "com.gzsys.modules.yun";
        boolean serviceNameStartWithI = false;//user -> UserService, 设置成true: user -> IUserService
        generateByTables(serviceNameStartWithI, packageName, "USER_LOGIN");
    }

    private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
        // 全局配置
        GlobalConfig config = new GlobalConfig();
        AutoGenerator mpg = new AutoGenerator();
        String dbUrl = "jdbc:oracle:thin:@//106.14.160.67:1521/test";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.ORACLE)
                .setUrl(dbUrl)
                .setUsername("test")
                .setPassword("Eru43wPo")
                .setDriverName("oracle.jdbc.driver.OracleDriver");
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true) // 全局大写命名 ORACLE 注意
                .setEntityLombokModel(false) //实体 是否为lombok模型(默认 false)
                .setDbColumnUnderline(true) //表名、字段名、是否使用下划线命名
                .setNaming(NamingStrategy.underline_to_camel) //表名生成策略
                .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
        // strategyConfig.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定义实体父类
        strategyConfig.setSuperEntityClass("com.gzsys.common.persistence.BaseEntity");
        // 自定义实体,公共字段
        strategyConfig.setSuperEntityColumns(new String[] { "ID", "CREATE_TIME", "CREATE_NAME" , "UPDATE_TIME", "UPDATE_NAME", "STATE"});
        // 自定义 mapper 父类
        // strategyConfig.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定义 service 父类
        //strategyConfig.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定义 service 实现类父类
        //strategyConfig.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定义 controller 父类
        strategyConfig.setSuperControllerClass("com.gzsys.common.base.controller.BaseController");
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
        // strategyConfig.setEntityColumnConstant(true);
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        // strategyConfig.setEntityBuliderModel(true);


        config.setActiveRecord(true) //是否 开启 ActiveRecord 模式
                .setAuthor("fendo")
                .setOutputDir("d:\\codeGen")
                .setFileOverride(true)
                .setActiveRecord(true)
                .setEnableCache(false)// XML 二级缓存
                .setBaseResultMap(true)// XML ResultMap
                .setBaseColumnList(false);// XML columList

        if (!serviceNameStartWithI) {
            config.setServiceName("%sService"); //自定义Service后戳,注意 %s 会自动填充表实体属性!
        }

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };


        // 自定义 xxList.jsp 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        //focList.add(new FileOutConfig("/template/list.jsp.vm") {
        //    @Override
        //    public String outputFile(TableInfo tableInfo) {
        //        // 自定义输入文件名称
        //        return "D://my_" + tableInfo.getEntityName() + ".jsp";
        //    }
        //});
        //cfg.setFileOutConfigList(focList);
        //mpg.setCfg(cfg);

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "d:\\codeGen/resources/mapping/modules/yun/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成,调整生成 至 根目录
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        // mpg.setTemplate(tc);

        //生成文件 配置
        mpg.setGlobalConfig(config)  //全局 相关配置
                .setDataSource(dataSourceConfig) //数据源配置
                .setStrategy(strategyConfig) //数据库表配置
                .setPackageInfo( //包 相关配置
                        new PackageConfig()  //跟包相关的配置项
                                .setParent(packageName)  //父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
                                .setController("controller") //Controller包名
                                .setEntity("entity") //entity包名
                                //.setXml("/")
                )
                .execute();
    }

    private void generateByTables(String packageName, String... tableNames) {
        generateByTables(true, packageName, tableNames);
    }

}

下文将讲解如何结合Swagger来使用!