springboot如何使用MybatisPlus

 更新时间:2024年09月09日 11:46:04   作者:BinaryBlade  
MyBatisPlus是一个强大的数据库操作框架,其代码生成器可以快速生成实体类、映射文件等,本文介绍了如何导入MyBatisPlus相关依赖,创建代码生成器,并配置数据库信息以逆向生成代码,感兴趣的朋友跟随小编一起看看吧

 MybatisPlus帮助文档地址:代码生成器 | MyBatis-Plus

 导入相关依赖

<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

第一个为MybatisPlus的起步依赖,后面两个依赖是为逆向生成服务的。

 代码生成器

package cn.xzit.springbootmybatisplus;
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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*该工具类用于生成实体类,mapper,service,controller
 * 用法:右键run该类,控制台输入表名,回车即可
 * */
/**
 * @author noBody
 */
public class CodeGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("jyz");
        gc.setOpen(false);
        gc.setBaseResultMap(true);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        //  pc.setModuleName(scanner("模块名"));
        pc.setParent("cn");/*生成的所有entity mapper等会放进主包里面*/
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
        // 自定义配置
        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";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapping/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
/*        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });*/
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        // strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

 创建一个generator包,包下面创建一个CodeGenerator类,类中放以上的代码,修改其中的数据库名和用户名以及密码,右键运行。输入需要逆向生成的表名,多个表用逗号隔开,然后回车。

注意要修改主包,我的主包为cn,读者可以自行修改代码中的setParent中的内容。

配置文件.yml文件

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
    hikari:
      connection-timeout: 6000
      maximum-pool-size: 5
#  jackson:
#    date-format: yyyy-MM-dd HH:mm:ss
#    time-zone: GMT+8
#    serialization:
#      write-dates-as-timestamps: false
mybatis-plus:
  configuration:
    #开启驼峰功能,数据库字段hello_world 实体类helloWorld 也能对应匹配
    map-underscore-to-camel-case: true
    #结果集自动映射(resultMap)
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapping/*Mapper.xml
  global-config:
    # 逻辑删除配置
    db-config:
      # 删除前
      logic-not-delete-value: 1
      # 删除后
      logic-delete-value: 0

到此这篇关于springboot使用MybatisPlus的文章就介绍到这了,更多相关springboot使用MybatisPlus内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈选择、冒泡排序,二分查找法以及一些for循环的灵活运用

    浅谈选择、冒泡排序,二分查找法以及一些for循环的灵活运用

    下面小编就为大家带来一篇浅谈选择、冒泡排序,二分查找法以及一些for循环的灵活运用。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • spring boot线上日志级别动态调整的配置步骤

    spring boot线上日志级别动态调整的配置步骤

    这篇文章主要为大家介绍了spring boot线上日志级别动态调整的配置步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • Java数据结构之平衡二叉树的实现详解

    Java数据结构之平衡二叉树的实现详解

    平衡二叉树又被称为AVL树(有别于AVL算法),且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。本文将详解介绍一下平衡二叉树的原理与实现,需要的可以参考一下
    2022-03-03
  • Java处理表格的实用工具库

    Java处理表格的实用工具库

    EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目,在尽可能节约内存的情况下支持读写百M的Excel,下面这篇文章主要给大家分享介绍了一个关于Java处理表格的实用工具库,需要的朋友可以参考下
    2021-11-11
  • Java线程池的拒绝策略实现详解

    Java线程池的拒绝策略实现详解

    这篇文章主要介绍了Java线程池的拒绝策略实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • Java去除字符串空格的几种方法简单举例

    Java去除字符串空格的几种方法简单举例

    在Java中要去掉字符串中的空格,可以使用多种方法,这篇文章主要给大家介绍了关于Java去除字符串空格的几种方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-12-12
  • MybatisPlus条件查询的具体使用

    MybatisPlus条件查询的具体使用

    MybatisPlus通过条件构造器可以组装复杂的查询条件,本文主要介绍了MybatisPlus条件查询的具体使用,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Spring Security如何优雅的增加OAuth2协议授权模式

    Spring Security如何优雅的增加OAuth2协议授权模式

    这篇文章主要介绍了Spring Security如何优雅的增加OAuth2协议授权模式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Spring框架应用的权限控制系统详解

    Spring框架应用的权限控制系统详解

    在本篇文章里小编给大家整理的是关于基于Spring框架应用的权限控制系统的研究和实现,需要的朋友们可以学习下。
    2019-08-08
  • SpringSecurity请求授权规则配置与注解详解

    SpringSecurity请求授权规则配置与注解详解

    这篇文章主要介绍了SpringSecurity请求授权规则配置与注解详解,我们常使用@Secured与@PreAuthorize两个注解在进入方法前进行角色、权限的控制,进入方法前数据的过滤@PreFilter注解偶尔会看到,需要的朋友可以参考下
    2023-12-12

最新评论