Mybatis-plus数据库自动生成

1.导入依赖文件:

<!--                   代码生成部分                -->
        <!-- Mybatis-plus 的 Spring boot 启动器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>

        <!-- Mybatis-plus 代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>

        <!-- spring boot 的 freemark 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!-- 数据库驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2.编写代码生成工具类: 

(1).需要导入的工具类

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Arrays;

(2).编写main方法

/**
 * MyBatis-Plus 代码生成类
 */
public class MyCodeGenerator {

    // TODO 修改! 服务名称
    private static final String SERVICE_NAME = "这里填数据库对应的服务名称!";

    // TODO 修改! 数据库账号
    private static final String DATA_SOURCE_USER_NAME = "你数据库的账号";

    // TODO 修改! 数据库密码
    private static final String DATA_SOURCE_PASSWORD = "你数据库的密码";

    // TODO 修改! 对应的表名
    private static final String[] TABLE_NAMES = new String[]{
            "你要使用代码生成工具生成的数据库中的表名"
    };

    // 默认生成entity,需要生成DTO修改此变量为true
    // 一般情况下要先生成 DTO类 然后修改此参数再生成 PO 类。
    private static final Boolean IS_DTO = false;

    //主方法
    public static void main(String[] args) {

        // TODO 修改!生成的文件的存储位置
        String targetDirectory = "你要将生成的文件存储的位置";

        // TODO 修改! 数据库URL
        String DBUrl = "jdbc:mysql://" + "你的数据库地址" + ":" + "你的数据库端口" + "/" + "数据库前缀" + SERVICE_NAME + "?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=utf8";

        // TODO 修改!数据库Driver [低版本:"com.mysql.jdbc.Driver"]
        String DBDriver="com.mysql.cj.jdbc.Driver";

        // TODO 修改! 父包
        String ParentPackage="你的父包";

        //当前所在目录,启动项目的容器位置,用IDEA是项目的根目录
        String currentDirectory = System.getProperty("user.dir");

        /* Mybatis-plus全局配置 */
        // 创建全局配置对象
        GlobalConfig gc = new GlobalConfig();
        // 设置为文件覆盖,防止生成错误
        gc.setFileOverride(true);
        // 禁用缓存功能 : 开启全局缓存功能可能会导致内存占用增加,同时需要合理设置缓存的更新策略,避免脏数据的影响
        gc.setOpen(false);
        // 禁用生成Swagger文档功能 : 开启需要先配置Swagger配置
        gc.setSwagger2(false);
        // 在XML映射文件中生成实体类的结果映射
        gc.setBaseResultMap(true);
        // 在XML映射文件中生成实体类的基本列列表
        gc.setBaseColumnList(true);
        // 生成对应的Service名字  : 这里使用了%s占位符
        gc.setServiceName("%sService");
        // 判断是否要生成实体类对应的Dto类
        if (IS_DTO) {
            gc.setEntityName("%sDTO");
        }
        // 生成路径
        gc.setOutputDir(currentDirectory + targetDirectory);

        /* 数据库配置 */
        // 创建数据库配置对象
        DataSourceConfig dsc = new DataSourceConfig();
        // 设置数据库类型为Mysql
        dsc.setDbType(DbType.MYSQL);
        // 数据库账号
        dsc.setUsername(DATA_SOURCE_USER_NAME);
        // 数据库密码
        dsc.setPassword(DATA_SOURCE_PASSWORD);
        // 数据库URL
        dsc.setUrl(DBUrl);
        // 数据库Driver
        dsc.setDriverName(DBDriver);

        /* 包配置 */
        // 创建包配置对象
        PackageConfig pc = new PackageConfig();
        // 设置模块名
        pc.setModuleName(SERVICE_NAME);
        // 设置父包,文件回存储到这个包下
        pc.setParent(ParentPackage);
        // 设置ServiceImpl所在包
        pc.setServiceImpl("service.impl");
        // 设置生成的Mapper.xml文件所在包
        pc.setXml("mapper");
        //设置生成的持久化对象所在包
        pc.setEntity("model.po");

        /* 策略配置 */
        // 创建策略配置对象
        StrategyConfig strategy = new StrategyConfig();
        //设置数据库表名转换为实体类名的命名策略,使用下划线转驼峰的命名方式
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //设置数据库列名转换为实体类属性名的命名策略,使用下划线转驼峰的方式
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //设置要生成实体类和相关代码的表名列表
        strategy.setInclude(TABLE_NAMES);
        //设置实体类使用Lombok插件自动生成Getters、Setters和构造方法等方法
        strategy.setEntityLombokModel(true);
        //设置实体类使用Lombok插件自动生成Getters、Setters和构造方法等方法
        strategy.setRestControllerStyle(true);
        //设置生成的Controller的@RequestMapping中的连字符形式[驼峰转连字符](具体值需要看模板中的情况)
        strategy.setControllerMappingHyphenStyle(true);
        // 设置生成的实体类对应的数据库表名前缀
        strategy.setTablePrefix(pc.getModuleName() + "_");
        // Boolean类型字段移除is前缀处理
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);
        // 设置自动填充字段配置
        strategy.setTableFillList(Arrays.asList(
                new TableFill("create_date", FieldFill.INSERT),
                new TableFill("change_date", FieldFill.INSERT_UPDATE),
                new TableFill("modify_date", FieldFill.UPDATE)
        ));

        /* 模板配置 */
        //创建模板配置对象[默认的模板是使用当前路径下的/templates/*]
        TemplateConfig tc = new TemplateConfig();

        /* 代码生成器及配置 */
        // 创建代码生成器对象
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Velocity
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 设置策略配置对象
        mpg.setStrategy(strategy);
        // 设置全局配置对象
        mpg.setGlobalConfig(gc);
        // 设置数据库配置对象
        mpg.setDataSource(dsc);
        // 设置包配置对象
        mpg.setPackageInfo(pc);
        // 设置模板配置对象
        mpg.setTemplate(tc);

        //启动代码生成任务
        mpg.execute();
    }
    
}

3.需要的mybatis-plus模板

[放到当前main方法所在项目目录的resources/templates目录下]

(1).controller.java.ftl

</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 */
@Slf4j
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
@RequestMapping("${entity?uncap_first}")
public class ${table.controllerName} {
</#if>

    @Autowired
    private ${table.serviceName}  ${table.serviceName?uncap_first};
}
</#if>

(2).entity.java.ftl

package ${package.Entity};

<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
</#if>
import com.baomidou.mybatisplus.annotation.TableName;

/**
 * <p>
 * ${table.comment!}
 * </p>
 */
<#if entityLombokModel>
@Data
</#if>
<#if !swagger2>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>

    private static final long serialVersionUID = 1L;
<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
    <#if field.keyFlag>
        <#assign keyPropertyName="${field.propertyName}"/>
    </#if>

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

<#if !entityLombokModel>
    <#list table.fields as field>
        <#if field.propertyType == "boolean">
            <#assign getprefix="is"/>
        <#else>
            <#assign getprefix="get"/>
        </#if>
    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}) {
        </#if>
        this.${field.propertyName} = ${field.propertyName};
        <#if entityBuilderModel>
        return this;
        </#if>
    }
    </#list>
</#if>

<#if entityColumnConstant>
    <#list table.fields as field>
    public static final String ${field.name?upper_case} = "${field.name}";

    </#list>
</#if>
<#if activeRecord>
    @Override
    protected Serializable pkVal() {
    <#if keyPropertyName??>
        return this.${keyPropertyName};
    <#else>
        return null;
    </#if>
    }

</#if>
<#if !entityLombokModel>
    @Override
    public String toString() {
        return "${entity}{" +
    <#list table.fields as field>
        <#if field_index==0>
        "${field.propertyName}=" + ${field.propertyName} +
        <#else>
        ", ${field.propertyName}=" + ${field.propertyName} +
        </#if>
    </#list>
        "}";
    }
</#if>
}

(3).mapper.java.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.springframework.stereotype.Repository;

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

}
</#if>

(4).service.java.ftl

package ${package.Service};

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

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

}
</#if>

(5).serviceImpl.java.ftl

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * ${table.comment!} 服务实现类
 * </p>
 */
@Slf4j
@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} {

}
</#if>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值