六、整合Mybatis Plus工具

上一篇:五、整合数据库连接池-Druid
在这里插入图片描述

一、Mybatis Plus

一个开源的,国内开发的Mybais增强工具,在Mybatis的基础上只做增强,不做改变,为简化开发、提高效率而生。

二、Mybatis Plus的核心功能

1、代码生成器:AutoGenerator

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

2、通用CRUD接口

Mybatis Plus在Mapper层(BaseMapper)及Service(IService)层都默认封装了通用的CRUD接口,可以极大的减少数据库操作业务代码

3、条件构造器

Wrapper 实体包装器,用于处理 sql 拼接,排序,实体参数查询等!

4、可扩展插件

  • 逻辑删除---- 为了方便数据恢复和保护数据本身价值等等的一种方案,并不从数据库移除记录,但实际就是删除

  • 分页插件---- 更方便的分页查询

  • 自动填充---- 数据创建或更新时触发自动填充字段

三、实践整合Mybatis Plus

创建spring-cloud-mybatis-plus项目,引入父工程作为版本控制

    <parent>
        <artifactId>spring-cloud-parent</artifactId>
        <groupId>com.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

第一步:引入依赖 mybatis-plus-boot-starter,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-parent</artifactId>
        <groupId>com.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mybatis</groupId>
    <artifactId>spring-cloud-mybatis-plus</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--oracle 驱动-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
        </dependency>

        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!--druid对spring监控需要的aop-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!--mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>

        <!--mybatis plus extension,包含了mybatis plus core-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
        </dependency>

        <!--代码生成器依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>

        <!--模板文件依赖-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.1</version>
        </dependency>

        <!--缓存依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!--作为web项目存在-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>
</project>

第二步:加配置,修改config模块中的datasource-mybatis-plus-dev.yml配置,增加mybatis-plus配置

在这里插入图片描述

spring:
  # 配置数据库信息
  datasource:
    # 数据源配置
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/spring?serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false  # 设置时区
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource   # 指定数据源为druid
    # 数据库连接池配置
    druid:
      # 初始化 最小 最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置多个英文逗号分隔
      filters: stat,wall

# mybatis-plus 配置
mybatis-plus:
  # mybatis的mapper文件扫描路径
  # 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
  # 如果是放在resource目录 classpath:/mapper/*Mapper.xml
  #  config-location: classpath:/mybatis/mybatis-config.xml
  mapper-locations: classpath:/mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.springcloud.demo.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 3
    # 热加载mapper文件
    refresh: true
    db-config:
      db-type: mysql
      #逻辑删除默认设置
      logic-delete-value: 1 #删除后的状态 默认值1
      logic-not-delete-value: 0 #逻辑前的值 默认值0

第三步:整合代码生成器,并使用代码生成器生成基本代码。

Mybatis Plus使用AutoGenerator作为代码生成器,实际上与Mybatis 的逆向工程是一个概念,只不过针对Mybatis
Plus做了一次封装,通过Mybatis的逆向工程与模板文件实现代码生成功能

1.数据库表:建立表格-client

CREATE TABLE `client` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `client_name` varchar(255) NOT NULL COMMENT '客户端名称',
  `client_path` varchar(255) DEFAULT NULL COMMENT '客户端路径',
  `del_flag` int(10) DEFAULT NULL COMMENT '逻辑删除标志',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '最后更新时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

在这里插入图片描述
2.引入模板依赖,本项目使用的是velocity模板(mybatis plus默认使用的模板)生成代码,故引入如下依赖:

<!--模板文件依赖-->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.1</version>
</dependency>

3.在comm-data模块中添加代码生成器工具类CodeGenerator(代码摘自官网示例,稍作更改):

package com.mybatis.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @description 代码生成工具演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
 * @auther: lai.guanfu
 * @date: 2019-05-23 15:06
 */
public class CodeGenerator {
    /**
     * 读取控制台内容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        //设置模板引擎为FreeMarker,默认引擎为Velocity
        //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        /** ======================================全局策略配置start=============================== **/
        String moudleName = scanner("模块名");
        String tableName = scanner("表名,多个英文逗号分割");
        //整体路径,默认所有自动生成代码归属于业务模块moudle总目录下的目标模块
        String projectPath = System.getProperty("user.dir")+StringPool.SLASH;
        //核验项目目录,如果项目不存在,不予创建生成代码
        File file = new File(projectPath);
        if(!file.exists()){
            throw new MybatisPlusException("请核验正确目录,当前项目不存在/n");
        }
        GlobalConfig gc = new GlobalConfig();
        //设置输出文件位置
        gc.setOutputDir(projectPath+ "/src/main/java");
        gc.setAuthor("lai.guanfu"); //作者
        gc.setOpen(false); //是否打开输出目录,默认为true
        gc.setFileOverride(false);// 是否覆盖同名文件,默认是false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setIdType(IdType.AUTO);//ID自增
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        //自定义Service的名称,如果不设置,默认Freemarker模板生成的Service类格式是:I%sService
        gc.setServiceName("%sService");
        gc.setBaseResultMap(true);
        mpg.setGlobalConfig(gc);
        /** ======================================全局策略配置end=============================== **/
        /** ======================================数据源配置【通过该配置,指定需要生成代码的具体数据库】start=============================== **/
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        /** ======================================数据源配置end=============================== **/
        /** ======================================数据库表配置【通过该配置,可指定需要生成哪些表或者排除哪些表】start=============================== **/
        StrategyConfig strategy = new StrategyConfig();
        //数据库表映射到实体的命名策略,此处指定下划线转小驼峰
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //数据库表字段映射到实体的命名策略,此处指定下划线转小驼峰
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //自定义继承的Entity类全称,带包名
        //strategy.setSuperEntityClass("com.springcloud.entity.BaseEntity");
        //是否为lombok模型
        strategy.setEntityLombokModel(true);
        //生成 @RestController 控制器
        strategy.setRestControllerStyle(true);
        //需要包含的表名,允许正则表达式(与exclude二选一配置),多个表格以英文逗号分隔
        strategy.setInclude(tableName.split(","));
        //strategy.setSuperEntityColumns("id");
        //驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        //是否生成实体时,生成字段注解
        strategy.setEntityTableFieldAnnotationEnable(true);
        //strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        /** ======================================数据库表配置end=============================== **/
        /** ======================================包名配置【通过该配置,指定生成代码的包路径】start=============================== **/
        PackageConfig pc = new PackageConfig();
        //父模块名,会拼接到父包名后面作为包
        //pc.setModuleName(scanner("模块名"));
        //父包名,如果为空,将下面子包名必须写全部, 否则就只需写子包名
        pc.setParent("com.springcloud.demo");
        mpg.setPackageInfo(pc);
        /** ======================================包名配置end=============================== **/
        /** ======================================注入配置【通过该配置,可注入自定义参数等操作以实现个性化操作】start=============================== **/
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 模板路径,如果模板引擎是 freemarker
        //String templatePath = "/templates/mapper.xml.ftl";
        // 模板路径,如果模板引擎是 velocity
        String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置文件(mapper.xml)
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        /** ======================================注入配置end=============================== **/
        /** ======================================模板配置【可自定义代码生成的模板,实现个性化操作】start=============================== **/
            // 配置模板
            TemplateConfig templateConfig = new TemplateConfig();

            // 配置自定义输出模板
            //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别,此处使用自带Freemarker模板即可
            // templateConfig.setEntity("templates/entity2.java");
            // templateConfig.setService();
            // templateConfig.setController();
            templateConfig.setController("/template/controller.java");
            templateConfig.setEntity("/template/entity.java");
            templateConfig.setMapper("/template/mapper.java");
            templateConfig.setXml("/template/mapper.xml");
            templateConfig.setService("/template/service.java");
            templateConfig.setServiceImpl("/template/serviceImpl.java");
            mpg.setTemplate(templateConfig);

            /** ======================================模板配置end=============================== **/
            mpg.execute();
        }
}

修改生成这些实体类的模板文件,我们可以看到mybatis plus generator的默认模板文件位于其jar包的templates目录下
在这里插入图片描述
复制模板到如下文件夹:
在这里插入图片描述
生成文件如下:
在这里插入图片描述

第四步:启动项目

  • 启动注册中心:spring-cloud-eureka-service
  • 启动配置中心:spring-cloud-config-service
  • 启动网关:spring-cloud-gateway
  • 启动本项目:spring-cloud-mybatis-plus

只有启动前三个项目,本项目才能启动, 启动成功,结果如下:

在这里插入图片描述

第五步:测试

直接用postman请求时404,原因是因为网关gateway没有配置请求权限
在这里插入图片描述
修改gateway配置文件如下,然后重启gateway:

server:
  port: 9999
spring:
  profiles:
    active: dev
  application:
    name: springcloud-gateway
  cloud:
    # 配置中心
    config:
      fail-fast: true
      name: ${spring.application.name}
      profile: ${spring.profiles.active}
      uri: http://localhost:8080

    #网关配置中心
    gateway:
      discovery:
        locator:  #路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。
          enabled: false #是否与服务发现组件进行结合,通过 serviceId(必须设置成大写) 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
          lower-case-service-id: true #允许通过模块名小写代理
      routes:
#        - id: springcloud-client
#          uri: lb://springcloud-client #网关路由到springcloud-client模块,lb指向内部注册模块
#          predicates: #转发谓词,用于设置匹配路由的规则
#            - Path=/client/** #通过请求路径匹配
#            - Method=GET #通过请求方式匹配
#  #            - RemoteAddr=127.0.0.1/25 #通过请求id匹配,只有在某个 ip 区间号段的请求才会匹配路由,其中/后的是子网掩码
#  #            - After=2018-01-20T06:06:06+08:00[Asia/Shanghai] #根据时间进行匹配,在指定时间之后才会匹配路由
#  #            - Before=2018-01-20T06:06:06+08:00[Asia/Shanghai] #根据时间进行匹配,在指定时间之前才会匹配路由
#  #            - Between=2018-01-20T06:06:06+08:00[Asia/Shanghai], 2019-01-20T06:06:06+08:00[Asia/Shanghai] #根据时间段进行匹配,处于指定时间段才会匹配路由
#          filters:
#            - RequestTime=true #此处仅需要配置过滤器工厂前缀及其属性值启动即可(注意“-”后面一定要跟空格,否则报错)
        - id: spring-cloud-druid
          uri: lb://spring-cloud-druid #网关路由到springcloud-client模块,lb指向内部注册模块
          predicates: #转发谓词,用于设置匹配路由的规则
            - Path=/spring-cloud-druid/** #通过请求路径匹配
          filters:
            - RequestTime=true
            - StripPrefix=1
        - id: spring-cloud-mybatis-plus
          uri: lb://spring-cloud-mybatis-plus #网关路由到springcloud-client模块,lb指向内部注册模块
          predicates: #转发谓词,用于设置匹配路由的规则
            - Path=/spring-cloud-mybatis-plus/** #通过请求路径匹配
          filters:
            - RequestTime=true
            - StripPrefix=1
  main:
    allow-bean-definition-overriding: true #是否允许同Bean覆盖

# 注册中心配置
eureka:
  instance:
    prefer-ip-address: true #优先使用IP地址注册
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/

再次测试如下,带上token
在这里插入图片描述

四、总结

1、Mybatis Plus是一个开源的,国内开发的Mybais增强工具,在Mybatis的基础上只做增强,不做改变,为简化开发、提高效率而生。

2、Mybatis Plus的核心功能分别有代码生成器、条件构造器和通用CRUD接口,还可以扩展常用插件,如分页插件,逻辑删除插件,自动填充插件等

五、资源地址

参考资源地址

下一篇:七、整合 Redis缓存

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老徐··

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值