springboot实现mybatis或者mybatisplus代码生成器功能

  • CodeGeneratorUtils代码(项目里面就这一个util工具类,还有个启动类项目自动成的)
  • controller.java.vm
  • entity.java.vm
  • ---------- BEGIN 字段循环遍历 ----------
  • mapper.java.vm
  • mapper.xml.vm
  • service.java.vm
  • serviceImpl.java.vm


##导入jar包(springboot版本对应2.5.0,如果比较老的版本,自己要切换mybatis-plus版本)

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

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

CodeGeneratorUtils代码(项目里面就这一个util工具类,还有个启动类项目自动成的)

package com.mybatis.code.utils;

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

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

public class CodeGeneratorUtils {

public static void main(String[] args) {
    //所有配置参考:https://mp.baomidou.com/config/generator-config.html#entity

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

    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java/");
    gc.setAuthor("lll");
    gc.setOpen(false);
    // gc.setSwagger2(true); 实体属性 Swagger2 注解
    //设置entity类的类名,%s为占位t符,即数据表转换过来的名字,相应的还可以设置mapper,service等的名字
    gc.setEntityName("%sPo");
    gc.setControllerName("%sController");
    mpg.setGlobalConfig(gc);

    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/ms?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8");
    // dsc.setSchemaName("public");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("root");
    mpg.setDataSource(dsc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    //一个项目的话可以不用
    pc.setModuleName(scanner("模块名"));
    pc.setParent("com.mybatis.code");
    // 设置ctroller的包名、不设置默认为cotroller,相应的还可以设置entity等所有的包名
    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 = "/myTemplates/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().replace("Po", "") + "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("myTemplates/entity.java");
     templateConfig.setService("myTemplates/service.java");
    templateConfig.setMapper("myTemplates/mapper.java");
    templateConfig.setServiceImpl("myTemplates/serviceImpl.java");
     templateConfig.setController("myTemplates/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.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 VelocityTemplateEngine());
    mpg.execute();
}

/**
 * <p>
 * 读取控制台内容
 * </p>
 */
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 + "!");
}

}

controller.java.vm

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * $!{table.comment} 前端控制器
 * @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

@Autowired
private ${table.serviceName} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Service;

@PostMapping("inset${entity}")
public Object inset${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
    $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Service.insert${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    return null;
}

@PostMapping("update${entity}")
public Object update${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
    $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Service.update${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    return null;
}

@PostMapping("delete${entity}")
public Object delete${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
    $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Service.delete${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    return null;
}

@PostMapping("select${entity}List")
public Object select${entity}List(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
    $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Service.select${entity}List($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    return null;
}

}
#end

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;
    #if(${chainModel})
    import lombok.experimental.Accessors;
    #end
#end

/**
 * $!{table.comment}
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
    #if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
    #else
@EqualsAndHashCode(callSuper = false)
    #end
    #if(${chainModel})
@Accessors(chain = true)
    #end
#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

#if(${entitySerialVersionUID})
private static final long serialVersionUID=1L;
#end

---------- 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 = "主键", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "主键", type = IdType.${idType})
#elseif(${field.convert})
@TableId("主键")
#end
## 普通字段
#elseif(${field.fill})
    ## -----   存在字段填充设置   -----
    #if(${field.convert})
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
    #else
    @TableField(fill = FieldFill.${field.fill})
    #end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#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(${chainModel})
    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(${chainModel})
            return this;
    #end
        }
    #end
    ## --foreach end---
#end
## --end of #if(!${entityLombokModel})--

#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.java.vm

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import java.util.List;
/**
 * <p>
 * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
    public void insert${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public void update${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public void delete${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public List<${entity}> select${entity}List(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
}
#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
    <!-- 通用查询映射结果 -->
    <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>

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

    <select id="select${entity}List" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from ${table.name}
        <where>

        </where>
    </select>

    <insert id="insert${entity}">
        insert into ${table.name}
        (
        #foreach($field in ${table.fields})
                ${field.name}#if($foreach.hasNext),#end
        #end
        )
        values
        (
        #foreach($field in ${table.fields})
                #{${field.propertyName}}#if($foreach.hasNext),#end
            #end
        )
    </insert>

    <update id="update${entity}">
        update ${table.name}
        <set>
            #foreach($field in ${table.fields})
                #if(!${field.keyFlag})##生成普通字段
                    ${field.name} =  #{${field.propertyName}}
                #end
            #end
        </set>
        <where>
            #foreach($field in ${table.fields})
                #if(${field.keyFlag})##生成主键排在第一位
                    ${field.name} = #{${field.propertyName}}
                #end
            #end
        </where>
    </update>

    <delete id="delete${entity}">
        delete from ${table.name}
        where
        #foreach($field in ${table.fields})
            #if(${field.keyFlag})##生成主键排在第一位
                ${field.name} = #{${field.propertyName}}
            #end
        #end
    </delete>
</mapper>

service.java.vm

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
 * $!{table.comment} 服务类
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
    public void insert${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public void update${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public void delete${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    public List<${entity}> select${entity}List(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)});
}
#end

serviceImpl.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;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
 * <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} {

    @Autowired
    private ${table.mapperName} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Mapper;

    @Override
    public void insert${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
       $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Mapper.insert${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    }
    @Override
    public void update${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
       $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Mapper.update${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    }

    @Override
    public void delete${entity}(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
    $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Mapper.delete${entity}($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    }

    @Override
    public List<${entity}> select${entity}List(${entity} $entity.substring(0, 1).toLowerCase()${entity.substring(1)}){
       return $entity.substring(0, 1).toLowerCase()${entity.substring(1)}Mapper.select${entity}List($entity.substring(0, 1).toLowerCase()${entity.substring(1)});
    }
}
#end

##实际效果(运行CodeGeneratorUtils的main方法就ok)

spring boot 生成banner spring boot代码生成器_spring boot