mybatis-plus代码生成器(二)

简介: mybatis-plus代码生成器(二)

没有斗争就没有功绩,没有功绩就没有奖赏,而没有行动就没有生活——别林斯基

之前写过一篇,不过当时是快照版直接跑在源码环境里,今天我们使用最新的api,并且使用GAV引入

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>

代码:

package com.ruben;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.jupiter.api.Test;
/**
 * 生成器配置
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/10/5 16:38
 */
public class GeneratorTests {
    /**
     * 生成代码的表名
     */
    private static final String TABLE_NAME = "user_info";
    /**
     * 数据库相关配置
     */
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    /**
     * 注释显示的作者
     */
    private static final String AUTHOR = "<achao1441470436@gmail.com>";
    /**
     * 代码生成指定包名
     */
    private static final String PACKAGE_NAME = "com.ruben";
    /**
     * 指定代码生成路径
     */
    private static final String OUTPUT_DIR = "D:\\file\\tmp\\generator\\output";
    /**
     * 模板存放路径
     */
    private static final String TEMPLATE_PATH = "./static/generator/";
    @Test
    public void generate() {
        System.out.println(OUTPUT_DIR);
        FastAutoGenerator.create(new DataSourceConfig.Builder(JDBC_URL, USERNAME, PASSWORD))
                // 全局配置
                .globalConfig(builder -> builder.author(AUTHOR).fileOverride().outputDir(OUTPUT_DIR))
                // 包配置
                .packageConfig(builder -> builder.parent(PACKAGE_NAME))
                // 策略配置
                .strategyConfig(builder -> builder
                        // 指定表名,如不指定,则默认生成所有
//                        .addInclude(TABLE_NAME)
                        .controllerBuilder().enableRestStyle()
                        .serviceBuilder()
                        .entityBuilder()
                        // 指定父类
                        .superClass(PACKAGE_NAME + ".pojo.common.BaseEntity")
                        // 添加父类字段
                        .addSuperEntityColumns("is_deleted", "gmt_create", "gmt_modified", "tenant_id")
                        // 开启AR模式
                        .enableActiveRecord()
                        // ID类型,这里IdType是个枚举
                        .idType(IdType.AUTO)
                        // 表名命名转换,这里是下划线转驼峰
                        .naming(NamingStrategy.underline_to_camel)
                        // 表字段名转换,下划线转驼峰
                        .columnNaming(NamingStrategy.underline_to_camel)
                        // 开启lombok
                        .enableLombok()
                        // 开启链式编程 (与BeanCopier冲突)
                        .enableChainModel())
                // 不生成xml
                .templateConfig(builder -> builder.disable(TemplateType.XML)
                        .controller(TEMPLATE_PATH + "controller.java.vm")
                        .entity(TEMPLATE_PATH + "entity.java.vm")
                        .mapper(TEMPLATE_PATH + "mapper.java.vm")
                        .service(TEMPLATE_PATH + "service.java.vm")
                        .serviceImpl(TEMPLATE_PATH + "serviceImpl.java.vm")
                )
                // 自定义模板位置
                .execute();
    }
}

以及自己使用的controller的模板:

package ${package.Controller};
#if(${restControllerStyle})
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruben.pojo.common.Result;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @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
    #set($serviceBeanName = $table.serviceName.substring(1,2).toLowerCase() + $table.serviceName.substring(2))
    #set($entityName = $entity.substring(0,1).toLowerCase() + $entity.substring(1))
    @Resource
    private ${table.serviceName} ${serviceBeanName};
    /**
     * 查询单条记录
     *
     * @param id 主键
     * @return 记录
     * @since ${date}
     * @author ${author}
     */
    @GetMapping
    public Result get(@RequestParam("id") Long id){
         return Result.ok().data(${entity}.builder().build().setId(id).selectById());
    }
    /**
     * 查询列表
     *
     * @param page 分页参数?size=10&current=1
     * @return 分页结果
     * @since ${date}
     * @author ${author}
     */
    @GetMapping("page")
    public Result page(Page<${entity}> page, ${entity} ${entityName}){
        return Result.ok().data(${entityName}.selectPage(page,Wrappers.lambdaQuery(${entityName})));
    }
    /**
     * 新增
     *
     * @param ${entityName} 数据
     * @since ${date}
     * @author ${author}
     */
    @PostMapping
    public Result insert(@RequestBody @Validated ${entity} ${entityName}){
        ${entityName}.insert();
        return Result.ok();
    }
    /**
     * 更新不为null的部分
     *
     * @param ${entityName} 数据
     * @since ${date}
     * @author ${author}
     */
    @PatchMapping
    public Result updateSelective(@RequestBody @Validated ${entity} ${entityName}){
        ${entityName}.updateById();
        return Result.ok();
    }
    /**
     * 根据主键删除
     *
     * @param id 主键
     * @since ${date}
     * @author ${author}
     */
    @DeleteMapping
    public Result delete(@RequestParam("id") Long id){
        ${entity}.builder().build().setId(id).deleteById();
        return Result.ok();
    }
}
#end
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.*;
    #if(${chainModel})
    import lombok.experimental.Accessors;
    #end
#end
/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
    #if(${chainModel})
    @Accessors(chain = true)
    #end
    #if(${superEntityClass})
    @EqualsAndHashCode(callSuper = true)
    #else
    @EqualsAndHashCode(callSuper = false)
    #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 = "${field.annotationColumnName}", type = IdType.AUTO)
        #elseif(!$null.isNull(${idType}) && "$!idType" != "")
        @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
        #elseif(${field.convert})
        @TableId("${field.annotationColumnName}")
        #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(${field.versionField})
    @Version
    #end
    ## 逻辑删除注解
    #if(${field.logicDeleteField})
    @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} && !${superEntityClass} )
@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
        }

entity


相关文章
|
4月前
|
SQL Java 数据库连接
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
MyBatis-Plus是一个MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。本文讲解了最新版MP的使用教程,包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段等核心功能。
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
|
5月前
|
Java 数据库连接 API
springBoot:后端解决跨域&Mybatis-Plus&SwaggerUI&代码生成器 (四)
本文介绍了后端解决跨域问题的方法及Mybatis-Plus的配置与使用。首先通过创建`CorsConfig`类并设置相关参数来实现跨域请求处理。接着,详细描述了如何引入Mybatis-Plus插件,包括配置`MybatisPlusConfig`类、定义Mapper接口以及Service层。此外,还展示了如何配置分页查询功能,并引入SwaggerUI进行API文档生成。最后,提供了代码生成器的配置示例,帮助快速生成项目所需的基础代码。
401 1
|
6月前
|
XML Java 关系型数据库
springboot 集成 mybatis-plus 代码生成器
本文介绍了如何在Spring Boot项目中集成MyBatis-Plus代码生成器,包括导入相关依赖坐标、配置快速代码生成器以及自定义代码生成器模板的步骤和代码示例,旨在提高开发效率,快速生成Entity、Mapper、Mapper XML、Service、Controller等代码。
springboot 集成 mybatis-plus 代码生成器
|
8月前
Mybatis-Plus 代码生成器
Mybatis-Plus 代码生成器
|
10月前
|
JavaScript Java 关系型数据库
SpringBoot + Mybatis + Vue的代码生成器
SpringBoot + Mybatis + Vue的代码生成器
143 2
|
10月前
|
JavaScript 关系型数据库 Java
MyBatisPlus 最新版代码生成器(直接拿来就能用,包含自动生成 Vue 模版)
MyBatisPlus 最新版代码生成器(直接拿来就能用,包含自动生成 Vue 模版)
1286 0
|
10月前
|
XML Java 数据库连接
MyBatis代码生成器
MyBatis代码生成器
156 0
|
10月前
|
SQL 资源调度 Java
mybatis-plus代码生成器的UI界面使用非常方便
mybatis-plus代码生成器的UI界面使用非常方便
165 0
|
10月前
如何使用MybatisPlus的代码生成器功能?
如何使用MybatisPlus的代码生成器功能?
|
10月前
|
数据库连接
一款非常好用的MyBatisPlus代码生成工具
一款非常好用的MyBatisPlus代码生成工具
53 0