springboot+mybatisPlus自动生成

生成准备

导入依赖

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

        <!--    代码生成器    -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

创建公共文件

创建接口Constants设置统一返回值。

public interface Constants {
    /**
     * 功能描述: 状态码
     *
     */
    String CODE_200 = "200"; //成功
    String CODE_400 = "400"; //参数错误
    String CODE_401 = "401"; //权限不足
    String CODE_500 = "500"; //系统错误
    String CODE_600 = "600"; //其他业务异常

    /**
     * 功能描述: 用户角色
     *
     */

    String DICT_TYPE_ICON = "icon"; //图标类型
}

创建R类。统一返回类。(记得使用lombok 加上注解@Data 全参构造 无参构造)

public class R {
    private String code; //状态码
    private String msg;  //提示信息
    private Object data; //返回数据

    public static R success(){
        return new R(Constants.CODE_200, "", null);
    }

    public static R success(Object data){
        return new R(Constants.CODE_200, "", data);
    }

    public static R error(String code, String msg){
        return new R(code, msg, null);
    }

    public static R error(){
        return new R(Constants.CODE_500, "系统错误", null);
    }



}

在resources目录下的templates文件中导入模板

模板1.controller.java.vm

package ${package.Controller};

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import common.R;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};

import org.springframework.web.bind.annotation.RequestMapping;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};import javax.annotation.Resource;
#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

    @Resource
    private ${table.serviceName} ${table.entityPath}Service;

    /**
     * 功能描述: 新增或更新
     *
     * @param ${table.entityPath}
     * @return
     * @throws
     * @Author: zn
     */
    @PostMapping("/save")
    public R save(@RequestBody ${entity} ${table.entityPath}) {
        ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
        return R.success();
    }

    /**
     * 功能描述: 删除
     *
     * @param id
     * @return
     * @throws
     * @Author: zn
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        ${table.entityPath}Service.removeById(id);
        return R.success();
    }

    /**
     * 功能描述: 批量删除
     *
     * @param ids
     * @return
     * @throws
     * @Author: zn
     */
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        ${table.entityPath}Service.removeByIds(ids);
        return R.success();
    }

    /**
     * 功能描述: 全查
     *
     * @param
     * @return
     * @throws
     * @Author: zn
     */
    @GetMapping("/findAll")
    public R findAll() {
        return R.success(${table.entityPath}Service.list());
    }

    /**
     * 功能描述: 单查
     *
     * @param id
     * @return
     * @throws
     * @Author: zn
     */
    @GetMapping("/findOne/{id}")
    public R findOne(@PathVariable Integer id) {
        return R.success(${table.entityPath}Service.getById(id));
    }

    /**
     * 功能描述: 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws
     * @Author: zn
     * @Date:   2022/7/28 19:15
     */
    @GetMapping("/findPage")
    public R findPage(@RequestParam Integer pageNum,
                      @RequestParam Integer pageSize) {
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return R.success(${table.entityPath}Service.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}
#end

模板2.entity.java.vm

package ${package.Entity};

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Getter
@Setter
  #if(${chainModel})
@Accessors(chain = true)
  #end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${swagger})
@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}> {
#elseif(${entitySerialVersionUID})
public class ${entity} implements Serializable {
#else
public class ${entity} {
#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(${swagger})
    @ApiModelProperty("${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})
    @Override
    public 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
}

模板3.mapper.java.vm

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
#if(${mapperAnnotation})
import org.apache.ibatis.annotations.Mapper;
#end

/**
 * <p>
 * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${mapperAnnotation})
@Mapper
#end
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
#end

模板4.service.java.vm

package ${package.Service};

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

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

}
#end

模板5.serviceImpl.java.vm

package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

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

    @Resource
    private ${table.mapperName} ${table.entityPath}Mapper;

}
#end

创建工具类Genertor,

在此文件中更改路径。配置数据库连接。设置生成的路径。点击运行。大功告成。

package com.buba.utils;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;

import java.util.Collections;

/**
 * @description:代码自动生成
 * @author: 张宁
 * @date: 2023/4/20 15:33
 * @param:
 * @return:
 **/
public class Generator {
//    public static void main(String[] args) {
//        generate();
//    }

    private static void generate(){
        //数据连接
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/test3?serverTimezone=Asia/Shanghai&useUnicode=true&" +
                                "characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true",
                        "root", "root")
                .globalConfig(builder -> {
                    builder.author("zn") // 设置作者
//                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件(已经过时)
                            .commentDate("yyyy-MM-dd")
                            .outputDir("D:\\idea\\ideaxiangmu\\userTest\\src\\main\\java\\"); // 指定输出目录 *
                })
                .packageConfig(builder -> {
                    builder.parent("com.buba") // 设置父包名 !!!
                            .moduleName(null) // 设置父包模块名
                            .mapper("mapper")
                            .xml("mapper")
                            .pathInfo(Collections.singletonMap(OutputFile.xml,
                                    "D:\\idea\\ideaxiangmu\\userTest\\src\\main\\resources\\mapper\\")); // 设置mapperXml生成路径 !!!
                })
                .strategyConfig(builder -> {
                    builder.addInclude("test_copy") // 设置需要生成的表名 !!!
                            .addTablePrefix("sys_")// 设置过滤表前缀 !!!
                            .serviceBuilder() //service生成策略
                            .formatServiceFileName("%sService")  //service类名,%s适配,根据表明替换
                            .formatServiceImplFileName("%sServiceImpl")  // service实现类
                            .entityBuilder()        //实体类生成策略
                            .enableLombok()         //开启lombok
//                            .logicDeleteColumnName("deleted")  //说明逻辑删除是哪个字段
                            .enableTableFieldAnnotation()  // 属性加上说明注解
                            .controllerBuilder()  //controller生成策略
                            .enableHyphenStyle() //开启驼峰转连字符
                            .formatFileName("%sController")
                            .enableRestStyle()  //开启RestController
                            .mapperBuilder()
                            .superClass(BaseMapper.class)  //dao层继承父类
                            .formatMapperFileName("%sMapper")
                            .enableMapperAnnotation() //@Mapper注解开启
                            .formatXmlFileName("%sMapper");
                })

//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值