mybatis-plus-generator3.5.1使用freemarker模板文件生成代码

不多说,直接上代码

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-freemarkerartifactId>
            <version>2.6.3version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-generatorartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.7.22version>
        dependency>

项目结构

mybatis-plus-generator3.5.1使用freemarker模板文件生成代码_第1张图片

代码生成工具类

package com.kun.gen;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * 代码生成
 * 注意: 请先修改resources目录下的generator.properties文件中的配置,无误则执行当前类下的main方法
 *
 * @author gzc
 * @since 2022/10/1 11:09
 **/
public class GenRun {

    /**
     * 代码生成入口
     * 注意: 请先修改resources目录下的generator.properties文件中的配置
     */
    public static void main(String[] args) {
        doGenerator();
        getPath();
    }

    private static Properties properties = new Properties();

    static {
        // 读取resources目录下的配置文件
        InputStream inputStream = GenRun.class.getClassLoader().getResourceAsStream("generator.properties");
        try {
            properties.load(IoUtil.getReader(inputStream, Charset.defaultCharset()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代码生成实现
     * 提示:如果不需要生成controller相关代码,设置packageConfig中的controller为"",设置templateConfig中的controller为null
     */
    private static void doGenerator() {
        // 建立数据库连接
        String url = properties.getProperty("database.url");
        String username = properties.getProperty("database.username");
        String password = properties.getProperty("database.password");
        DataSourceConfig dsc = new DataSourceConfig.Builder(url, username, password).build();

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator(dsc);
        // 模块名称
        String moduleName = properties.getProperty("moduleName");
        // 项目目录
        String projectPath = properties.getProperty("projectPath");
        // 作者名称
        String author = properties.getProperty("author");
        // 基础包路径
        String packagePath = properties.getProperty("packagePath");
        // 需要生成的表
        String tables = properties.getProperty("tables");
        // 代码生成后是否打开磁盘目录
        String openDir = properties.getProperty("openDir");

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig
                .Builder()
                .outputDir(projectPath + "/" + moduleName + "/src/main/java")
                .author(author)
//                .openDir("true".equals(openDir))
                .commentDate("yyyy-MM-dd HH:mm:ss")
                .build();

        // 包配置
        PackageConfig packageConfig = new PackageConfig
                .Builder()
                .parent(packagePath)
//                .moduleName(moduleName)
                .controller("")
                .entity("entity.po")
                .mapper("mapper")
                .service("service")
                .serviceImpl("service.impl")
                .moduleName(null)
                .build();

        // 配置模板
        String absolutePath = File.separator + "templates";
        String mapperTempPath = absolutePath + File.separator + "MapperP";
        String entityTempPath = absolutePath + File.separator + "EntityP";
        String serviceTempPath = absolutePath + File.separator + "ServiceP";
        String serviceImplTempPath = absolutePath + File.separator + "ServiceImplP";
        TemplateConfig templateConfig = new TemplateConfig
                .Builder()
                .mapper(mapperTempPath)
                .service(serviceTempPath)
                .serviceImpl(serviceImplTempPath)
                .entity(entityTempPath)
                .mapperXml(null)
                .controller(null)
                .build();

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig
                .Builder()
                .addInclude(tables.split(","))
                .entityBuilder()
                .naming(NamingStrategy.underline_to_camel)
//                .enableLombok()
//                .controllerBuilder()
//                .enableRestStyle()
                .build();

        mpg.global(globalConfig);
        mpg.packageInfo(packageConfig);
        mpg.template(templateConfig);
        mpg.strategy(strategyConfig);
        // 开始生成代码文件
        mpg.execute(new FreemarkerTemplateEngine());
    }


    /**
     * 获取当前项目本地磁盘目录
     */
    private static void getPath() {
        System.out.println("当前项目本地磁盘目录->" + System.getProperty("user.dir"));
    }

}

配置文件 generator.properties

# 生成目录 示例 D:/project/idea-project/kun-cloud
projectPath=D:/project/idea-project/kun-cloud
# 模块名称 示例 kun-modules/kun-blog
moduleName=kun-modules/kun-blog
# 基础包路径 示例 com.kun.blog
packagePath=com.kun.blog
# 作者
author=xxx
# 需要生成的表名,多个表用逗号分割
tables=emoji_type,emoji

# 数据库连接配置
database.url=jdbc:mysql://127.0.0.1:3306/kun-blog?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true
database.username=root
database.password=root

生成的代码时基于mybatis-plus的,给出的模板文件按自己的需求进行修改即可

EntityP.ftl

package ${package.Entity};

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

<#assign a = 0>
<#assign b = 0>
<#assign c = 0>
<#list table.fields as field>
	<#if field.propertyType = "LocalDateTime" && a = 0>
import java.time.LocalDateTime;
        <#assign a = a + 1>
	</#if>
    <#if field.propertyType = "LocalDate" && b = 0>
import java.time.LocalDate;
        <#assign b = b + 1>
    </#if>
    <#if field.propertyType = "BigDecimal" && c = 0>
import java.math.BigDecimal;
        <#assign c = c + 1>
    </#if>
</#list>

/**
 * ${table.comment!}
 *
 * @author ${author}
 * @since ${date}
 */
@Data
@TableName("${table.name}")
public class ${entity} {

<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
	/**
	 * ${field.comment}
	 */
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>
    <#if field.keyFlag>
    <#-- 主键 -->
        <#if field.keyIdentityFlag>
	@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
        <#elseif idType??>
	@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
        <#elseif field.convert>
	@TableId("${field.annotationColumnName}")
        </#if>
    <#-- 普通字段 -->
    <#elseif field.fill??>
    <#-- -----   存在字段填充设置   ----->
        <#if field.convert>
	@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
        <#else>
	@TableField(fill = FieldFill.${field.fill})
        </#if>
    <#elseif field.convert>
	@TableField("${field.annotationColumnName}")
    </#if>
<#-- 乐观锁注解 -->
    <#if (versionFieldName!"") == field.name>
	@Version
    </#if>
<#-- 逻辑删除注解 -->
    <#if (logicDeleteFieldName!"") == field.name>
	@TableLogic
    </#if>
	private ${field.propertyType} ${field.propertyName};
</#list>
<#------------  END 字段循环遍历  ---------->
}

MapperP.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import com.kun.common.database.mapper.CoreMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * ${table.comment!}${table.name}表持久层接口
 *
 * @author ${author}
 * @since ${date}
 */
@Mapper
public interface ${table.mapperName} extends CoreMapper<${entity}> {

}

ServiceP.ftl

package ${package.Service};

import ${package.Entity}.${entity};
import com.kun.common.database.service.BaseService;

/**
 * ${table.comment!}业务接口
 *
 * @author ${author}
 * @since ${date}
 */
public interface I${entity}Service extends BaseService<${entity}>{

}

ServiceImplP.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.I${entity}Service;
import com.kun.common.database.service.impl.BaseServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ${entity}ServiceImpl extends BaseServiceImpl<${table.mapperName}, ${entity}> implements I${entity}Service {


}

运行main方法

mybatis-plus-generator3.5.1使用freemarker模板文件生成代码_第2张图片
mybatis-plus-generator3.5.1使用freemarker模板文件生成代码_第3张图片

就此完成!!!

你可能感兴趣的:(mybatis,mybatis,java,spring,boot)