2022/5/25 Mybatis-Plus代码生成器(mybatis-plus-generat)配置模板

目录

1.导入依赖

2.编写配置类

3.运行配置类

4.结果

        4.1 controller层

        4.2 entity层

        4.3 Mapper层

        4.4 Mapper.xml层

        4.5 Service层

        4.6 ServiceImp层


1.导入依赖

  <!--引入MybatisPlus核心配置文件-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--代码生成器-->
        <!--当前包未传递依赖 MP 包,需要自己引入!-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- 模板生成器引擎配合代码生成器一起使用 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

2.编写配置类

package com.hzf.books;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.fill.Property;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/**
 * @program: 梦进大厂
 * @description: mybatis-plus-generator代码生成器
 * @author: Mr.Abcdzzr
 * @create: 2022-05-25 23:12
 **/
public class CodeGenerator {

    public static void main(String[] args) {
        /*数据库配置*/
        //数据库改成自己的
        DataSourceConfig dataSourceConfig =
                new DataSourceConfig
                        .Builder("jdbc:mysql://localhost:3306/bookdb?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true","root","123123")
                        .dbQuery(new MySqlQuery())
                        .build();


        /*创建一共代码生成器对象*/
        AutoGenerator generator = new AutoGenerator(dataSourceConfig);



        //String property = System.getProperty(scanner("请输入项目路径"));


        /*全局配置*/
        GlobalConfig globalConfig = new GlobalConfig.Builder()
                .fileOverride()
                .outputDir(scanner("请输入你的项目路径") + "/src/main/java")
                .author("HuangZhuFang").disableOpenDir()
                //.enableKotlin()
                //.enableSwagger()
                .dateType(DateType.TIME_PACK)
                .commentDate("yyyy-MM-dd")
                .build();



        generator.global(globalConfig);


        /*包配置(PackageConfig)*/
        PackageConfig packageConfig = new PackageConfig.Builder()
                .parent("com.hzf.books")    //这里改成自己对应的包名
                //.moduleName("blog")
                .entity("entity")
                .service("service")
                .serviceImpl("service.impl")
                .mapper("mapper")
                .xml("mapper")
                .controller("controller")
                //.other("other")
                //.pathInfo(Collections.singletonMap(OutputFile.mapper, "D://"))
                //.pathInfo(Collections.singletonMap(OutputFile.xml, "D://"))
                .build();

        generator.packageInfo(packageConfig);


        TemplateConfig templateConfig = new TemplateConfig.Builder()
                .disable(TemplateType.ENTITY)
                .entity("/templates/entity.java")
                .service("/templates/service.java")
                .serviceImpl("/templates/serviceImpl.java")
                .mapper("/templates/mapper.java")
                .xml("/templates/mapper.xml")
                .controller("/templates/controller.java")
                .build();

        generator.template(templateConfig);

        /*策略配置*/
        StrategyConfig strategyConfig = new StrategyConfig.Builder()
                .enableCapitalMode()
                .enableSkipView()
                .disableSqlFilter()
                //.likeTable(new LikeTable("USER"))
                .addInclude(getTables(scanner("请输入表名,多个英文逗号分隔?所有输入 all")))
                .addTablePrefix("book_")    //去掉表中的前缀
                //.addFieldSuffix("_flag")
                /*   .entityBuilder()
                   .controllerBuilder()
                   .mapperBuilder()
                   .serviceBuilder()*/
                .build();

        strategyConfig.entityBuilder()
                //.superClass(BaseEntity.class)
                .disableSerialVersionUID()
                .enableChainModel()
                .enableLombok()
                .enableRemoveIsPrefix()
                .enableTableFieldAnnotation()
                .enableActiveRecord()
                .versionColumnName("version")
                .versionPropertyName("version")
                .logicDeleteColumnName("deleted")
                .logicDeletePropertyName("deleted")
                .naming(NamingStrategy.underline_to_camel)  //开启驼峰命名映射表中字段
                .columnNaming(NamingStrategy.underline_to_camel)
                //.addSuperEntityColumns("id", "created_by", "created_time", "updated_by", "updated_time")
                //.addIgnoreColumns("age")
                .addTableFills(new Column("create_time", FieldFill.INSERT))
                .addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
                .idType(IdType.AUTO)
                .formatFileName("%s")
                .build();

        strategyConfig.controllerBuilder()
                //.superClass(BaseController.class)
                //.enableHyphenStyle()
                .enableRestStyle()
                .formatFileName("%sController")
                .build();

        strategyConfig.serviceBuilder()
                //.superServiceClass(BaseService.class)
                // .superServiceImplClass(BaseServiceImpl.class)
                .formatServiceFileName("%sService")
                .formatServiceImplFileName("%sServiceImp")
                .build();

        strategyConfig
                .mapperBuilder()
                .superClass(BaseMapper.class)
                //.enableMapperAnnotation()
                //.enableBaseResultMap()
                //.enableBaseColumnList()
                //.cache(MyMapperCache.class)
                .formatMapperFileName("%sMapper")
                .formatXmlFileName("%sMapper")
                .build();


        generator.strategy(strategyConfig);

        /*执行代码生成器*/
        generator.execute();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

    /**
     * <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.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
}

3.运行配置类

请输入请输入你的项目路径:
D:\黄朱方\books
请输入请输入表名,多个英文逗号分隔?所有输入 all:
all
23:19:12.165 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
23:19:12.193 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.unicode' has been deprecated in favor of 'resource.loader.file.unicode'
23:19:12.194 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.class' has been deprecated in favor of 'resource.loader.file.class'
23:19:12.381 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show table status WHERE 1=1 
23:19:12.406 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:2,耗时(ms):25
23:19:12.460 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `book_info`
23:19:12.462 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[book_info]的主键为自增主键,会导致全局主键的ID类型设置失效!
23:19:12.470 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:10,耗时(ms):10
23:19:12.508 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 执行SQL:show full fields from `users`
23:19:12.509 [main] WARN com.baomidou.mybatisplus.generator.IDatabaseQuery$DefaultDatabaseQuery - 当前表[users]的主键为自增主键,会导致全局主键的ID类型设置失效!
23:19:12.509 [main] DEBUG com.baomidou.mybatisplus.generator.config.querys.MySqlQuery - 返回记录数:7,耗时(ms):1
23:19:12.523 [main] DEBUG org.apache.velocity - Initializing Velocity, Calling init()...
23:19:12.523 [main] DEBUG org.apache.velocity - Starting Apache Velocity v2.3
23:19:12.526 [main] DEBUG org.apache.velocity - Default Properties resource: org/apache/velocity/runtime/defaults/velocity.properties
23:19:12.537 [main] DEBUG org.apache.velocity - ResourceLoader instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.538 [main] DEBUG org.apache.velocity - initialized (class org.apache.velocity.runtime.resource.ResourceCacheImpl) with class java.util.Collections$SynchronizedMap cache map.
23:19:12.539 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Stop
23:19:12.540 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Define
23:19:12.540 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Break
23:19:12.541 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Evaluate
23:19:12.541 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Macro
23:19:12.542 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Parse
23:19:12.543 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Include
23:19:12.544 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach
23:19:12.559 [main] DEBUG org.apache.velocity.parser - Created '20' parsers.
23:19:12.573 [main] DEBUG org.apache.velocity.macro - "velocimacro.library.path" is not set. Trying default library: velocimacros.vtl
23:19:12.574 [main] DEBUG org.apache.velocity.loader.file - Could not load resource 'velocimacros.vtl' from ResourceLoader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.574 [main] DEBUG org.apache.velocity.macro - Default library velocimacros.vtl not found. Trying old default library: VM_global_library.vm
23:19:12.574 [main] DEBUG org.apache.velocity.loader.file - Could not load resource 'VM_global_library.vm' from ResourceLoader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.574 [main] DEBUG org.apache.velocity.macro - Old default library VM_global_library.vm not found.
23:19:12.574 [main] DEBUG org.apache.velocity.macro - allowInline = true: VMs can be defined inline in templates
23:19:12.574 [main] DEBUG org.apache.velocity.macro - allowInlineToOverride = false: VMs defined inline may NOT replace previous VM definitions
23:19:12.574 [main] DEBUG org.apache.velocity.macro - allowInlineLocal = false: VMs defined inline will be global in scope if allowed.
23:19:12.574 [main] DEBUG org.apache.velocity.macro - autoload off: VM system will not automatically reload global library macros
23:19:12.594 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/entity.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.607 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.612 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.xml.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.618 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/service.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.623 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/serviceImpl.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.630 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/controller.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.637 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/entity.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.643 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.648 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.xml.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.653 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/service.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.658 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/serviceImpl.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.662 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/controller.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:19:12.666 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================

进程已结束,退出代码为 0

4.结果

        4.1 controller层

package com.hzf.books.controller;

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

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HuangZhuFang
 * @since 2022-05-25
 */
@RestController
@RequestMapping("/info")
public class InfoController {

}

        4.2 entity层

package com.hzf.books.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 com.baomidou.mybatisplus.extension.activerecord.Model;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author HuangZhuFang
 * @since 2022-05-25
 */
@Getter
@Setter
@Accessors(chain = true)
@TableName("book_info")
public class Info extends Model<Info> {

    /**
     * 图书id
     */
    @TableId(value = "book_id", type = IdType.AUTO)
    private Integer bookId;

    /**
     * 图书编号
     */
    @TableField("book_code")
    private String bookCode;

    /**
     * 图书名称
     */
    @TableField("book_name")
    private String bookName;

    /**
     * 图书类型(1、小说、2、文学、3、传记、4、艺术、5、少儿、6、经济、7、管理、8、科技)
     */
    @TableField("book_type")
    private Integer bookType;

    /**
     * 图书作者
     */
    @TableField("book_atuthor")
    private String bookAtuthor;

    /**
     * 出版社
     */
    @TableField("publish_press")
    private String publishPress;

    /**
     * 是否借阅(1、已借阅0、未借阅
     */
    @TableField("is_borrowed")
    private Integer isBorrowed;

    /**
     * 创建人
     */
    @TableField("created_by")
    private String createdBy;

    /**
     * 创建时间
     */
    @TableField("creation_time")
    private LocalDateTime creationTime;

    /**
     * 最后更新时间
     */
    @TableField("last_update_time")
    private LocalDateTime lastUpdateTime;


    @Override
    public Serializable pkVal() {
        return this.bookId;
    }

}

        4.3 Mapper层

package com.hzf.books.mapper;

import com.hzf.books.entity.Info;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author HuangZhuFang
 * @since 2022-05-25
 */
public interface InfoMapper extends BaseMapper<Info> {

}

        4.4 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="com.hzf.books.mapper.InfoMapper">

</mapper>

        4.5 Service层

package com.hzf.books.service;
import com.hzf.books.entity.Info;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author HuangZhuFang
 * @since 2022-05-25
 */
public interface InfoService extends IService<Info> {

}

        4.6 ServiceImp层

package com.hzf.books.service.impl;

import com.hzf.books.entity.Info;
import com.hzf.books.mapper.InfoMapper;
import com.hzf.books.service.InfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangZhuFang
 * @since 2022-05-25
 */
@Service
public class InfoServiceImp extends ServiceImpl<InfoMapper, Info> implements InfoService {

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abcdzzr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值