美文网首页Java
mybaties-plus-generator反向生成2020完

mybaties-plus-generator反向生成2020完

作者: 木木呦 | 来源:发表于2020-02-27 22:25 被阅读0次

我的开发工具

       idea + springboot

github代码地址

先展示效果

controller 实体类 mapper文件 mapper.xml service实现类 service接口

目录结构

目录结构

即粘即用的文件

  1. pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mutu.plus</groupId>
    <artifactId>plus-generaor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>plus-generaor</name>
    <description>mybaties-plus逆向工程</description>

    <properties>
        <java.version>1.8</java.version>
        <mybatis-plus.version>3.3.0</mybatis-plus.version>
        <packaging>jar</packaging>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.mutu.plus.MybatiesPlusGenerator</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.xml</exclude>
                    <exclude>**/*.yml</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>
  1. MybatiesPlusGenerator.java
package com.mutu.plus;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
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 org.springframework.context.annotation.PropertySource;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

@PropertySource(value = {"classpath: local.properties", "file:${spring.profiles.path}/local.properties"}, ignoreResourceNotFound = true)
public class MybatiesPlusGenerator {

    public static void main(String[] args) {

        Properties properties;
        try {
            properties = new Properties();
            // jar包传配置文件形式
            String filePath = "local.properties";
            // 读取resources下的配置文件
//            String filePath = "src/main/resources/local.properties";
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            properties.load(new InputStreamReader(in, "UTF-8"));
        }catch (Exception e){
            e.printStackTrace();
            return;
        }

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + properties.getProperty("output.dir", "/src/main/java"));
        gc.setAuthor(properties.getProperty("author", "nobody"));
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(properties.getProperty("data.url"));
        dsc.setDriverName(properties.getProperty("data.driver.name"));
        dsc.setUsername(properties.getProperty("data.username"));
        dsc.setPassword(properties.getProperty("data.password"));
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(properties.getProperty("model.name"));
        pc.setParent(properties.getProperty("model.parent", "com"));
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                HashMap<String, Object> map = new HashMap<>();
                map.put("nameSpace", pc.getParent());
                this.setMap(map);
            }
        };

        // Mapper.xml文件生成。如果模板引擎是 freemarker
        String templatePath = properties.getProperty("templatePath", "/templates/mapper.xml.ftl");

        // 自定义mapper.xml配置
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/java/com/baomidou/" + pc.getModuleName()
                        + "/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        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(properties.getProperty("super.entity.class"));
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(Boolean.valueOf(properties.getProperty("rest.controller")));
        // 公共父类
        strategy.setSuperControllerClass(properties.getProperty("super.controller.class"));
        strategy.setInclude(properties.getProperty("tables").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
  1. local.properties
# MySQL数据库配置
data.username = root
data.password = 123456
data.url = jdbc:mysql://192.168.19.135:3306/mutu?characterEncoding=utf-8&useSSL=false
data.driver.name = com.mysql.jdbc.Driver

# 类注释上的@author 默认:nobody,如果乱码,改为txt格式,另存为utf-8再改回properties后缀
author = 野猪屁奇
# 输出根目录 默认:/src/main/java
output.dir = /src/main/java

# 包配置
model.parent = com.baomidou
# 模块名
model.name = model
# mapper.xml模板路径, freemarker.ftl  velocity.vm
templatePath = /templates/mapper.xml.ftl

# 表名,多个表使用逗号分隔
tables = USER
# 实体类是否继承父类 值为父类路径 例如:com.entity.BaseEntity
super.entity.class =
# Controller类是否继承父类 值为父类路径 例如:com.entity.BaseController
super.controller.class =
# Controller注解类型  true:@RestController  false: @controller
rest.controller = false
  1. mapper.xml.ftl mapper.xml模板文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${cfg.nameSpace}.mapper.${table.entityName}Mapper">



</mapper>
  1. PlusGeneraorApplication.java 没有改动,为了小白还是贴出来
package com.mutu.plus;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PlusGeneraorApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlusGeneraorApplication.class, args);
    }

}

以上,执行MybatiesPlusGenerator中的main方法即可生成

下面介绍,通过jar包,引用外部配置文件,灵活生成

1. 生成jar包

生成jar包

2. target文件夹下生成jar包了

image.png

3. 把local.properties复制一份放进来

image.png

执行程序

输入cmd回车
# 输入命令
java -jar plus-generaor-0.0.1-SNAPSHOT.jar --spring.config.location=local.properties
cmd

相关文章

网友评论

    本文标题:mybaties-plus-generator反向生成2020完

    本文链接:https://www.haomeiwen.com/subject/bdyfhhtx.html