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

2023-11-06

一、简介


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项目,然后加入以下依赖:

<?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配置文件

# 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

/**
 * 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表

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测试类如下:

/**
 * 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

/**
 * 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来使用!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MyBatis-Plus系列(一)--MyBatis-Plus集成Druid环境搭建 的相关文章

随机推荐

  • 2021蒙城高考成绩查询,2021亳州高考成绩查询入口

    今年的高考已经和大家告一段落 想必考生和家长们现在比较关注的就是高考成绩查询了 下面出国留学网小编给大家分享 2021亳州高考成绩查询入口 仅供参考 希望帮助各位考生便捷查询高考成绩 祝大家考个好成绩 2021安徽高考成绩查询时间 2021
  • cmd命令安装python第三方库_Python如何安装第三方库

    Python如何安装第三方库 版权申明 非商业目的注明出处可自由转载 博文地址 https blog csdn net cdpxc article details 108808780 出自 cdpxc 注 笔者是在D盘直接安装了Anacon
  • VAE,变分

    1 Latent Variable Model 生成模型一般会生成多个种类的数据 比如说在手写数字生成中 我们总共有10个类别的数字要生成 这个时候latent variable model就是一个很好的选择 为什么呢 举例来说 我们很容易
  • 使用tika 判断文件类型

    判断文件类型一般可采用两种方式 后缀名判断 简单易操作 但无法准确判断类型 文件头信息判断 通常可以判断文件类型 但有些文件类型无法判断 如word和excel头信息的前几个字节是一样的 无法判断 Apache Tika 是什么 Apach
  • gru matlab实现,分别用CNN、GRU和LSTM实现时间序列预测(2019-04-06)

    卷积神经网络 CNN 长短期记忆网络 LSTM 以及门控单元网络 GRU 是最常见的一类算法 在kaggle比赛中经常被用来做预测和回归 今天 我们就抛砖引玉 做一个简单的教程 如何用这些网络预测时间序列 因为是做一个简单教程 所以本例子中
  • 【QT】判断本地语言

    QLocale ql switch ql language case QLocale Chinese 系统语言是中文 可以进行其他操作 break default break
  • 模块之间的耦合与内聚的七种类型

    文章目录 前言 按功能划分的四种模块类型 七种耦合 1 非直接耦合 2 数据耦合 3 标记耦合 4 控制耦合 5 外部耦合 6 公共耦合 7 内容耦合 七种内聚 1 偶然 巧合 内聚 2 逻辑内聚 3 时间内聚 4 通信内聚 5 顺序内聚
  • 常用 Git 命令清单

    常用 Git 命令清单 文章目录 常用 Git 命令清单 在当前目录新建一个Git代码库 新建一个目录 将其初始化为Git代码库 下载一个项目和它的整个代码历史 显示当前的Git配置 编辑Git配置文件 设置提交代码时的用户信息 添加指定文
  • 编码规范C/C++

    一 命名 1 类型名 使用首字母大写的驼峰命名法 如StudentGrade MyClass 命名由单词组合而成 其中每个单词以大写字母开头 不包含下划线 宏 常量 enum 结构中的成员命名全部大写 2 变量 语义上应该是一个名词或名词短
  • 大学计算机基础字母缩写大全,大学计算机基础缩写词.pdf

    大学计算机基础缩写词 1 ALU Arithmetic Logic Unit 算术逻辑单元 2 CPU Central Processing Unit 中央处理单元 3 CISC 技术 ComplexInstructionSetComput
  • windows10右下角网络图标不见,而且设置里面是灰色的

    打开任务管理器 把资源管理器右键重新启动
  • Variable used in lambda expression should be final or effectively final报错解决方案

    Variable used in lambda expression should be final or effectively final报错解决方案 问题背景 解决方案 Lyric 哪里都是你 问题背景 在使用forEach报错 Va
  • 比double精度更高的数据类型_数据类型

    两个重点 数据类型 变量 数据类型 Data Type 数据类型就是数据的类型 每种数据有自己的值和操作规则 C 有三大类语句类型 简单数据类型 结构化据类型 点 这一期只详细讲简单数据类型 另外两个类型的会分别单独做一期 简单数据类型 S
  • Faster Rcnn

    一 公用特征Feature Maps的获取 二 Region Proposal Network Feature Maps bs 1024 38 38 经过3 3卷积 然后分别经过两个1 1的卷积 通道数分别为18 36 18 9 2 代表每
  • JDBC-查询数据(封装工具类)

    使用封装工具类方式查询数据 1 封装注册 连接 关闭工具类 public class JdbcUtils 设置属性 驱动 private static String driver 连接 private static String url m
  • 算法课程设计--A*算法解决特定条件下的最短路径问题

    1 算法课设题目 LOL 峡谷地图最优路径规划 以下问题的计算 按照该地图的基本规则来进行在该地图中分布着各种形状不规则的障碍区域环境 整个地图模型 可以根据需求进行自行简化 问题一 在任意起点与终点之间 规划一条最短路径 问题二 当你拥有
  • 亚信科技AntDB数据库参与“国内首款”事务型性能测试工具开源发布会,树立金融技术风向标

    日前 在中国信息通信研究院和中国通信标准化协会大数据技术标准推进委员会共同举办的 国内首款金融数据库性能测试工具DataBench T开源发布会 上 亚信科技受邀进行了 亚信科技数据库测试之道 的主旨演讲 图1 中国信通院DataBench
  • 基于TensorFlow让机器生成赵雷曲风的歌词

    本文转载自公众号量化投资与机器学习 ZXL LHTZ JQXX 原文 致敬赵雷 基于TensorFlow让机器生成赵雷曲风的歌词 责编 王艺 投稿及采访请邮件wangyi csdn net 或 扫描文末二维码 我们基本上收集了赵雷所有唱过的
  • 狂神说Es

    在学习ElasticSearch之前 先简单了解一下Lucene Doug Cutting开发 是apache软件基金会4 jakarta项目组的一个子项目 是一个开放源代码的全文检索引擎工具包 不是一个完整的全文检索引擎 而是一个全文检索
  • MyBatis-Plus系列(一)--MyBatis-Plus集成Druid环境搭建

    一 简介 Mybatis Plus是一款 MyBatis 动态 sql 自动注入 crud 简化 增 删 改 查 操作中间件 启动加载 XML 配置时注入 mybatis 单表 动态 SQL 操作 为简化开发工作 提高生产率而生 Mybat