# 生成CRUD代码

代码生成

  • spring-boot-plus在mybatis-plus基础上,新增param/vo等模板
  • 拓展controller/service/mapper/xml,生成通用CRUD/分页方法

# 5分钟完成增删改查

# 1. 创建数据库表

-- ----------------------------
-- Table structure for foo_bar
-- ----------------------------
DROP TABLE IF EXISTS `foo_bar`;
CREATE TABLE `foo_bar`
(
    `id`            bigint(20)  NOT NULL COMMENT '主键',
    `name`          varchar(20) NOT NULL COMMENT '名称',
    `foo`           varchar(20)          DEFAULT NULL COMMENT 'Foo',
    `bar`           varchar(20) NOT NULL COMMENT 'Bar',
    `remark`        varchar(200)         DEFAULT NULL COMMENT '备注',
    `state`         int(11)     NOT NULL DEFAULT '1' COMMENT '状态,0:禁用,1:启用',
    `version`       int(11)     NOT NULL DEFAULT '0' COMMENT '版本',
    `create_time`   timestamp   NULL     DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time`   timestamp   NULL     DEFAULT NULL COMMENT '修改时间',
    PRIMARY KEY (`id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4
  COLLATE = utf8mb4_general_ci COMMENT ='FooBar';

-- ----------------------------
-- Records of foo_bar
-- ----------------------------
INSERT INTO foo_bar (id, name, foo, bar, remark, state, version, create_time, update_time) 
    VALUES (1, 'FooBar', 'foo', 'bar', 'remark...', 1, 0, '2019-11-01 14:05:14', null);
INSERT INTO foo_bar (id, name, foo, bar, remark, state, version, create_time, update_time) 
    VALUES (2, 'HelloWorld', 'hello', 'world', null, 1, 0, '2019-11-01 14:05:14', null);

# 2.使用代码生成器生成CURD代码

代码生成入口类,在generator模块中

spring-boot-plus/generator/src/main/java/io/geekidea/springbootplus/generator/SpringBootPlusGenerator.java
/**
 * spring-boot-plus代码生成器入口类
 *
 * @author geekidea
 * @date 2019-10-22
 **/
@Component
public class SpringBootPlusGenerator {

    /**
     * 生成代码
     * @param args
     */
    public static void main(String[] args) {
        GeneratorProperties generatorProperties = new GeneratorProperties();

        // 设置基本信息
        generatorProperties
                .setMavenModuleName("example")
                .setParentPackage("com.example")
                .setModuleName("foobar")
                .setAuthor("geekidea")
                .setFileOverride(true);

        // 设置表信息
        generatorProperties.addTable("foo_bar","id");
        // 设置表前缀
        // generatorProperties.setTablePrefix(Arrays.asList("tb_"));

        // 数据源配置
        generatorProperties.getDataSourceConfig()
                .setDbType(DbType.MYSQL)
                .setUsername("root")
                .setPassword("root")
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl("jdbc:mysql://localhost:3306/spring_boot_plus?useUnicode=true&characterEncoding=UTF-8&useSSL=false");

        // 生成配置
        generatorProperties.getGeneratorConfig()
                .setGeneratorStrategy(GeneratorStrategy.SINGLE)
                .setGeneratorEntity(true)
                .setGeneratorController(true)
                .setGeneratorService(true)
                .setGeneratorServiceImpl(true)
                .setGeneratorMapper(true)
                .setGeneratorMapperXml(true)
                .setGeneratorPageParam(true)
                .setGeneratorQueryVo(true)
                .setRequiresPermissions(false)
                .setPageListOrder(true)
                .setParamValidation(true)
                .setSwaggerTags(true)
                .setOperationLog(true);

        // 全局配置
        generatorProperties.getMybatisPlusGeneratorConfig().getGlobalConfig()
                .setOpen(true)
                .setSwagger2(true)
                .setIdType(IdType.AUTO)
                .setDateType(DateType.ONLY_DATE);

        // 策略配置
        generatorProperties.getMybatisPlusGeneratorConfig().getStrategyConfig()
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setEntityLombokModel(true)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                .setVersionFieldName(GeneratorConstant.VERSION)
                .setLogicDeleteFieldName(GeneratorConstant.DELETED);

        // 生成代码
        CodeGenerator codeGenerator = new CodeGenerator();
        codeGenerator.generator(generatorProperties);

    }
}

注意

  • 直接执行SpringBootPlusGenerator.java即可生成代码,生成代码后会打开文件目录
  • 支持多表同时生成,支持表前缀自定义生成,支持表主键名不为id的情况等
  • 更多代码生成常见问题:👉 https://springboot.plus/faq/generator.html

特别注意

  • 支持三种生成模式:SIMPLE:生成最基本的代码,SINGLE:生成单表操作代码,ALL:生成所有的代码
  • SIMPLE:生成entity及其它文件的基本代码结构
  • SINGLE:生成单表操作,包含entity及其它文件的CURD代码,注意,不包含VO!!!
  • ALL:生成单表最全代码,包含entity及其它文件的CURD代码,包含VO

# 代码生成日志





























 
 
 
 
 
 
 
 
 
 
 
 
 





23:21:55.656 [main] INFO io.geekidea.springbootplus.generator.CodeGenerator - outputDir: /Users/geekidea/github/spring-boot-plus/example
23:21:55.670 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
23:21:56.356 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.unicode' has been deprecated in favor of 'resource.loader.file.unicode'
23:21:56.356 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.class' has been deprecated in favor of 'resource.loader.file.class'
23:21:56.358 [main] DEBUG org.apache.velocity - Initializing Velocity, Calling init()...
23:21:56.358 [main] DEBUG org.apache.velocity - Starting Apache Velocity v2.2
23:21:56.361 [main] DEBUG org.apache.velocity - Default Properties resource: org/apache/velocity/runtime/defaults/velocity.properties
23:21:56.368 [main] DEBUG org.apache.velocity - ResourceLoader instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.369 [main] DEBUG org.apache.velocity - initialized (class org.apache.velocity.runtime.resource.ResourceCacheImpl) with class java.util.Collections$SynchronizedMap cache map.
23:21:56.371 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Stop
23:21:56.373 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Define
23:21:56.373 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Break
23:21:56.374 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Evaluate
23:21:56.374 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Macro
23:21:56.376 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Parse
23:21:56.377 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Include
23:21:56.377 [main] DEBUG org.apache.velocity - Loaded System Directive: org.apache.velocity.runtime.directive.Foreach
23:21:56.403 [main] DEBUG org.apache.velocity.parser - Created '20' parsers.
23:21:56.428 [main] DEBUG org.apache.velocity.macro - "velocimacro.library.path" is not set. Trying default library: velocimacros.vtl
23:21:56.429 [main] DEBUG org.apache.velocity.loader.file - Could not load resource 'velocimacros.vtl' from ResourceLoader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.429 [main] DEBUG org.apache.velocity.macro - Default library velocimacros.vtl not found. Trying old default library: VM_global_library.vm
23:21:56.429 [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:21:56.429 [main] DEBUG org.apache.velocity.macro - Old default library VM_global_library.vm not found.
23:21:56.429 [main] DEBUG org.apache.velocity.macro - allowInline = true: VMs can be defined inline in templates
23:21:56.429 [main] DEBUG org.apache.velocity.macro - allowInlineToOverride = false: VMs defined inline may NOT replace previous VM definitions
23:21:56.429 [main] DEBUG org.apache.velocity.macro - allowInlineLocal = false: VMs defined inline will be global in scope if allowed.
23:21:56.429 [main] DEBUG org.apache.velocity.macro - autoload off: VM system will not automatically reload global library macros
23:21:56.452 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.xml.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.489 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.xml.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/resources/mapper/foobar/FooBarMapper.xml
23:21:56.491 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/pageParam.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.494 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/pageParam.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/param/FooBarPageParam.java
23:21:56.503 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/entity.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.507 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/entity.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/entity/FooBar.java
23:21:56.509 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/mapper.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.510 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/mapper.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/mapper/FooBarMapper.java
23:21:56.512 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/service.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.513 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/service.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/service/FooBarService.java
23:21:56.516 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/serviceImpl.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.517 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/serviceImpl.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/service/impl/FooBarServiceImpl.java
23:21:56.523 [main] DEBUG org.apache.velocity.loader - ResourceManager: found /templates/controller.java.vm with loader org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
23:21:56.524 [main] DEBUG com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine - 模板:/templates/controller.java.vm;  文件:/Users/geekidea/github/spring-boot-plus/example/src/main/java/com/example/foobar/controller/FooBarController.java
23:21:56.544 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================

Process finished with exit code 0

# 3.生成的代码结构

└── src
    └── main
        ├── java
        │   └── com
        │       └── example
        │           └── foobar
        │               ├── controller
        │               │   └── FooBarController.java
        │               ├── entity
        │               │   └── FooBar.java
        │               ├── mapper
        │               │   └── FooBarMapper.java
        │               ├── param
        │               │   └── FooBarPageParam.java
        │               ├── service
        │               │   ├── FooBarService.java
        │               │   └── impl
        │               │       └── FooBarServiceImpl.java
        │               └── vo
        │                   └── FooBarQueryVo.java
        └── resources
            └── mapper
                └── foobar
                    └── FooBarMapper.xml

# 4. 代码生成器模版

使用Velocity模版生成代码,可自定义修改代码生成模版

spring-boot-plus/generator/src/main/resources
└── templates
    ├── controller.java.vm      控制器代码生成模版
    ├── entity.java.vm          实体类代码生成模版
    ├── mapper.java.vm          mapper代码生成模版
    ├── mapper.xml.vm           mapper xml 代码生成模版
    ├── pageParam.java.vm       分页参数代码生成模版
    ├── queryVo.java.vm         查询结果代码生成模版
    ├── service.java.vm         服务接口代码生成模版
    └── serviceImpl.java.vm     服务实现代码生成模版