MyBatis plus generator自动生成Dao层

目录结构:

 生成代码类

 

package com.asinking.cloud.uc.admin.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 自动生成dao,mapper文件的类
 * </p>
 *
 * @author by duanfeixia
 * @version 1.0
 * @since 2023/7/11 11:05
 */
public class UCGeneratorApplication {

    private static final String dbUrl = "jdbc:mysql://10.11.0.43:3306/data01";
    private static final String dbUsername = "www";
    private static final String dbPassword = "root";
    private static final String authorName = "root11";

    public static void main(String[] args) {
        List<String> tables = new ArrayList<>();
        tables.add("user_bak_001");
        tables.add("user_auto_001");

        FastAutoGenerator.create(dbUrl,dbUsername,dbPassword)
                .globalConfig(builder -> {
                    builder.author(authorName)
                            .outputDir(System.getProperty("user.dir")+"\\ak-uc-dao\\src\\main\\java")    //输出路径(写到java目录)
                            .enableSwagger()           //开启swagger
                            .commentDate("yyyy-MM-dd")
                            .fileOverride();            //开启覆盖之前生成的文件
                })
                .packageConfig(builder -> {
                    builder.parent("com.asinking.cloud.uc.admin")
                            .entity("entity")
                            .mapper("mapper")
                            .xml("mapper")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml,System.getProperty("user.dir")+"\\ak-uc-dao\\src\\main\\resources\\mapper"));
                })
                .strategyConfig(builder -> {
                    builder.addInclude(tables)
//                            .serviceBuilder()
//                            .formatServiceFileName("%sService")
//                            .formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder()
                            .enableLombok()
                            .enableTableFieldAnnotation()
//                            .controllerBuilder()
//                            // 映射路径使用连字符格式,而不是驼峰
//                            .enableHyphenStyle()
//                            .enableRestStyle()
                            .mapperBuilder()
                            .formatMapperFileName("%sMapper")
                            .enableMapperAnnotation()
                            .formatXmlFileName("%sMapper");
                })
                .templateConfig(builder -> { // 不生成 service和controller
                    builder.service("")
                            .serviceImpl("")
                            .controller("");
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }

}

 

 

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>ak-uc</artifactId>
        <groupId>com.asinking.cloud</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ak-uc-generator</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <mybatis-plus-generator.version>3.5.1</mybatis-plus-generator.version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-generator.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
    </dependencies>

</project>

 

 

 

===========================================================================================================================

最近在搞生成包的问题,发现Mybatis plus不需要一张一张表的配置耶,所以就有了下文啦哈哈哈~

主要步骤:

1.新建基于SpringBoot的Maven项目,引入相关依赖

2.参考官方文档配置生成包的信息,编写生成generated包的主要类

3.新建模板信息(如果有自己特殊的要求的话,没有使用默认的即可)

4.将生成包打包测试 然后就可以开始使用啦~

 

整体项目目录结构如下(红色标记的文件为手动新增的内容):

 

1.新建基于SpringBoot 的 Maven项目,pom.xml如下(我这里用的mysql8.x的,可根据实际情况更改数据库驱动包哈)

<?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.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.imodule.product</groupId>
    <artifactId>product</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>product</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <imodule-nexus.version>0.0.1-SNAPSHOT</imodule-nexus.version>
        <quartz.version>2.3.0</quartz.version>
        <org.slf4j-version>1.6.4</org.slf4j-version>

    </properties>


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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <!--mybatis-plus自动的维护了mybatis以及mybatis-spring的依赖,
          在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

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

        </plugins>
    </build>
</project>


2.主要配置类 CodeGenerator.java

整个生成过程中 最值得讲的就是此类了,这里我连的TiDB数据库(类似与MySQL,直接用mysql的驱动即可)

细节一:策略配置 StrategyConfig 指定数据库中哪些表需要生成Dao

String[] tablename = {"PRD_BASE","PRD_PROPERTY"}; //多张表用数组表示

strategy.setInclude(tablename);// 包含那些表,excude排除哪些表 include与excude只能设置一个(如果不添加此项配置 默认生成数据库中所有的表对应的Dao)

 

细节二:由于我们是用的TiDB数据库,这不是我们原来的业务数据库,所以需要从其它库传输数据到TiDB,子啊通过DataPipeline传输的时候,发现DataPipeline有个自动的功能,当它发现同步的表没有主键的时候会自动建立列 _id 作为这张表的主键,同步到TiDB指定库中,这就给我们带来了难题, _id 字段在通过mybatis plus generator生成后,属性名为 id ,去掉了前缀 _ ,当我们执行查询的时候就会找不到 id字段,手动注释掉这个 id字段后,数据又正常啦。所以我们就更改了模板文件新增了 #if判断,就是在字段迭代的时候先判断当前字段是不是 _id,如果是就不做任何操作,也就是不将此属性添加到对象总,如果不是就正常执行。

#if(${field.name.equals("_id")})

语句如下:

#foreach($field in ${table.fields})
#if(${field.name.equals("_id")})
#else
...中间省略原来的模板代码信息...
private ${field.propertyType} ${field.propertyName};
#end
#end

 

细节三:模板配置 StrategyConfig的setTablePrefix方法,我原以为是可以手动添加表前缀,结果测试发现这是去掉前缀的意思。

示例:

数据库表名称为 PRD_USER

设置 StrategyConfig.setTablePrefix("PRD_");

最后生成的实体类: User ,去掉了 PRD_ 前缀 (除了实体类 Mapper Service Controller都会统一去掉 PRD_前缀)

如果不设置的话tablePrefix的话,生成的实体类为 PrdUser  (Mapper Service Controller都类似)

 

细节四:模板配置 TemplateConfig 指定生成的结果文件模板信息 (结果文件中需要包含哪些 语法参考对应的引擎)

templateConfig.setEntity("templates/entity.java"); 
templateConfig.setMapper("templates/mapper.java"); templateConfig.setXml("templates/mapper.xml"); templateConfig.setService("templates/service.java"); templateConfig.setServiceImpl("templates/serviceImpl.java"); templateConfig.setController("templates/controller.java");

这里我们使用TiDB,打算用同一套数据源,里面包含多个数据库(意思就是同一个数据库服务器里面建立多个数据库,类似与DBLINK),系统需要具备跨库查询的功能,直接生成的话是无法查询其它数据库的数据库的

所以我们在模板上做了一些小改造:在表名前增加了库名(目前没有参数可以设置,所以我们就直接在entity.java.vm模版文件中更改了,文章最后会提供更改之后的Entity模板文件)

原来是: @TableName("${table.name}")

更改后: @TableName("prd_demo.${table.name}")  //在这里把库名固定了 (如果有多个库需要分别生成,每次生成前需要先更改这个schema name 数据库名称)


package cozhelim.imodule.product;


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.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CodeGenerator {

    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("jobob");
        gc.setOpen(false);
       // gc.setIdType(null);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://10.11.22.33:4000/prd_demo?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("product");//scanner("模块名")
        pc.setParent("com.imodule.product");
        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/mapper/" + 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/entity.java");
        templateConfig.setMapper("templates/mapper.java");
        templateConfig.setXml("templates/mapper.xml");
        templateConfig.setService("templates/service.java");
        templateConfig.setServiceImpl("templates/serviceImpl.java");
        templateConfig.setController("templates/controller.java");

        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.setSuperMapperClass("");
        strategy.setSuperServiceClass("");
        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");*/
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类

        // 写于父类中的公共字段
        String[] tablename = {"PRD_BASE","PRD_PROPERTY"};
        strategy.setInclude(tablename);// 包含那些表,excude排除哪些表,多张表用数组表示
        strategy.setControllerMappingHyphenStyle(true);


        //eg: tablename: PRD_USER,StrategyConfig.setTablePrefix("PRD");   生成的实体类: User
        //  strategy.setTablePrefix(new String[]{"PRD","demo_"});//去掉生成的实体类的前缀
        // strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.setTemplateEngine(new VelocityTemplateEngine());//更改模板引擎

        /**
         * 这一段是为了测试看看里面包含些啥 可以忽略
         */
        ConfigBuilder configBuilder = new ConfigBuilder( pc,  dsc,  strategy,  templateConfig,  gc);
        MySqlQuery mySqlQuery =new MySqlQuery();
        String sql =  mySqlQuery.tablesSql();
        log.info("tidb sql:"+sql);// show table status
        List<TableInfo>  tableinfo = configBuilder.getTableInfoList();
        for(TableInfo table:tableinfo){
            log.info("tidb tableinfo:"+table.getEntityName());
            log.info("tidb tableinfo:"+table.getXmlName());

        }

        mpg.execute();
    }

}

  

3. 这里用的是 VM模板,模板文件分别如下(解压官方mybatis-plus-generator-3.0.5.jar,在mybatis-plus-generator-3.0.5\templates目录下 获取的)

 

 entity.java.vm(默认的)

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${swagger2})
@ApiModel(value="${entity}对象", description="$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

private static final long serialVersionUID = 1L;
## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
    #if(${swagger2})
    @ApiModelProperty(value = "${field.comment}")
    #else
    /**
     * ${field.comment}
     */
     #end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
    @TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
    @TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
    @TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
#if(${field.convert})
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
    @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
    @TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
    @Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
    private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

    public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }

#if(${entityBuilderModel})
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
        this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
        return this;
#end
    }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
    @Override
    protected Serializable pkVal() {
#if(${keyPropertyName})
        return this.${keyPropertyName};
#else
        return null;
#end
    }

#end
#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
        "${field.propertyName}=" + ${field.propertyName} +
#else
        ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
        "}";
    }
#end
}

  

mapper.xml.vm(默认的)

<?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="${package.Mapper}.${table.mapperName}">

#if(${enableCache})
    <!-- 开启二级缓存 -->
    <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

#end
#if(${baseResultMap})
    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
        <id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
    <result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
        <result column="${field.name}" property="${field.propertyName}" />
#end
#end
    </resultMap>

#end
#if(${baseColumnList})
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
        ${field.name},
#end
        ${table.fieldNames}
    </sql>

#end
</mapper>

   

mapper.java.vm(默认的)

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
    @Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
#end

  

service.java.vm(默认的)

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};

/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

}
#end

  

seviceimpl.java.vm(默认的)

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;

/**
 * <p>
 * $!{table.comment} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

}
#end

  

controller.java.vm(默认的)

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end

}

#end

  

4.主类设计 ProductApplication.java

package com.imodule.product;

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

@SpringBootApplication
public class ProductApplication {
    /**
     * springboot 项目主启动类
     * @param args main 函数入参
     */
    public static void main(String[] args) {
        SpringApplication.run(ProductApplication.class, args);
    }
}

 

执行步骤: 直接执行 CodeGenerator.java的main方法就可以了啦

执行结果: (红色框框标记的文件均为自动生成的)

 

5.做个测试吧,我们可以就在这个项目里面添加数据源配置信息 写测试类开始测试啦

添加数据源配置:

 

测试类编写:PrdBaseMapperTest.java

package com.imodule.product.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imodule.product.product.entity.PrdBase;
import com.imodule.product.product.mapper.PrdBaseMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;

import java.util.Arrays;
import java.util.List;

//@RunWith(SpringRunner.class)
@ContextConfiguration
@SpringBootTest
class PrdBaseMapperTest {
   @Autowired
    private PrdBaseMapper prdBaseMapper;

    @Test
    public void testPrdBaseMapper(){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("columnname","columnvalue");//这里写对应的列名与列值即可
        List<PrdBase> prdbase = prdBaseMapper.selectList(queryWrapper);
        System.out.println("testPrdBaseMapper result:"+prdbase);
    }

}

  

测试结果 欧克啦啦啦啦~

完整的生成流程就如上所述啦~

 

最后提供一下更改之后的entity模板文件(基于VM)

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
#if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
#else
@EqualsAndHashCode(callSuper = false)
#end
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("prd_prd.${table.name}")
#end
#if(${swagger2})
@ApiModel(value="${entity}对象", description="$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

    private static final long serialVersionUID = 1L;
## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
#if(${field.name.equals("_id")})
#else
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
    #if(${swagger2})
    @ApiModelProperty(value = "${field.comment}")
    #else
    /**
     * ${field.comment}
     */
     #end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
    @TableId(value = "${field.name}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
    @TableId(value = "${field.name}", type = IdType.${idType})
#elseif(${field.convert})
    @TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
#if(${field.convert})
    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
    @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
    @TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
    @Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
    private ${field.propertyType} ${field.propertyName};
#end
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

    public ${field.propertyType} ${getprefix}${field.capitalName}() {
        return ${field.propertyName};
    }

#if(${entityBuilderModel})
    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
        this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
        return this;
#end
    }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
    public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
    @Override
    protected Serializable pkVal() {
#if(${keyPropertyName})
        return this.${keyPropertyName};
#else
        return null;
#end
    }

#end
#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
        "${field.propertyName}=" + ${field.propertyName} +
#else
        ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
        "}";
    }
#end
}

  

 posted on 2020-03-27 19:38  阿叮339  阅读(2861)  评论(0编辑  收藏  举报