mybatis-plus自定义代码生成

项目结构

  • 该生成器代码是用于多个模块之间的生成
    在这里插入图片描述

BasePojo

  • 实体类的父类,减少字段的编写
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BasePojo {
	// 主键
    @TableId(type = IdType.AUTO)
    private Integer id;

 	// 分页的页码 根据自己是否需要
    @JsonIgnore
    @TableField(exist = false)
    private Integer page =1;

	// 每页的大小 根据自己是否需要
    @JsonIgnore
    @TableField(exist = false)
    private Integer limit=5;

	// 是否分页 1 分页 0 不分页 根据自己是否需要
    @JsonIgnore
    @TableField(exist = false)
    private Integer withPage =1;
    
    @TableField("active")
    private Integer active;

    @TableField("create_time")
    private LocalDateTime createTime;

    @TableField("update_time")
    private LocalDateTime updateTime;
}

CodeGenerator

public class CodeGenerator {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir") + "/";
        // 子项目名称
        String projectName = "admin";
        // pojo项目名称
        String pojoName = "pojo";

        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setFileOverride(true);// 覆盖已有文件
        gc.setAuthor("liuyong");
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/adms?useSSL=false&serverTimezone=Asia/Shanghai");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("654321");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.neuedu");
        pc.setEntity("pojo");
        pc.setService("service");
        pc.setMapper("mapper");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");

        // 定义生成文件的位置
        Map<String, String> pathInfo = new HashMap<>();
        pathInfo.put("entity_path", projectPath + pojoName + "/src/main/java/com/neuedu/pojo");
        pathInfo.put("mapper_path", projectPath + projectName + "/src/main/java/com/neuedu/mapper");
        pathInfo.put("service_path", projectPath + projectName + "/src/main/java/com/neuedu/service");
        pathInfo.put("service_impl_path", projectPath + projectName + "/src/main/java/com/neuedu/service/impl");
        pathInfo.put("controller_path", projectPath + projectName + "/src/main/java/com/neuedu/controller");
        pc.setPathInfo(pathInfo);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + projectName + "/src/main/resources/com/neuedu/mapper"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setController("controllerInit.java");

        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // 数据库表映射到实体的命名策略
        strategy.setNaming(NamingStrategy.underline_to_camel);
        // 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 自定义继承的Entity类
        strategy.setSuperEntityClass(BasePojo.class);
        // 自定义基础的Entity类,公共字
        strategy.setSuperEntityColumns("id", "active", "update_time", "create_time");
        // 使用 lombok模型
        strategy.setEntityLombokModel(true);
        // 生成 @RestController 控制器
        strategy.setRestControllerStyle(true);
        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        // 生成表名时去除前缀
        strategy.setTablePrefix("sys");
        // 生成实体时,生成字段注解
        strategy.setEntityTableFieldAnnotationEnable(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

controllerInit.java.ftl

package ${package.Controller};

import java.util.Map;
import javax.annotation.Resource;

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

import com.neuedu.util.CommonResult;
import com.neuedu.util.InitUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.web.bind.annotation.*;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * <p>
 * ${table.comment!} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
    private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Resource
    private ${table.serviceName} i${entity}Service;

    /**
    * 进行分页查询
    */
    @GetMapping
    public CommonResult getList(@RequestParam Map<String, Object> param) {
        InitUtil.initPage(param);
        int num = Integer.parseInt(param.get("page").toString());
        int limit = Integer.parseInt(param.get("limit").toString());
        QueryWrapper<${entity}> wrapper = new QueryWrapper<>();
        InitUtil.initEq(param, wrapper, "active");
        IPage<${entity}> page = new Page<>(num, limit);
        return CommonResult.success(i${entity}Service.page(page, wrapper));
    }

    /**
     * 通过主键id在表中查找信息
    */
    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable int id) {
        ${entity} i${entity} = i${entity}Service.getById(id);
        if (i${entity} == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(i${entity});
    }

    /**
    * name : 需要检查那个字段的value是否在数据库存在
    * 比如/check/RegistworkName?value=阿司匹林  :检查数据库是否存在RegistworkName='阿司匹林'
    */
    @GetMapping("/check/{name}")
    public CommonResult checkName(@PathVariable String name,@RequestParam String value){
        QueryWrapper<${entity}> wrapper = new QueryWrapper<>();
        wrapper.eq(name, value);
        if (i${entity}Service.getOne(wrapper) != null){
            return CommonResult.failed();
        }
        return CommonResult.success();
    }

    /**
     * 向表中添加一条记录
    */
    @PostMapping()
    public CommonResult save(@RequestBody ${entity} i${entity}) {
        if (i${entity}Service.save(i${entity})){
            return CommonResult.successMsg("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * 根据表中的主键修改 根据表中字段相应的修改,如果存在则修改
    */
    @PutMapping("/{id}")
    public CommonResult update(@RequestBody ${entity} i${entity}, @PathVariable int id) {
        i${entity}.setId(id);
        if (i${entity}Service.updateById(i${entity})){
            return CommonResult.successMsg("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    /**
     * active 字段 相当于激活一样 设置字段的有效性 active=1 有效
    */
    @PutMapping("/back/{id}")
    public CommonResult back(@PathVariable int id) {
        ${entity} i${entity} = new ${entity}();
        i${entity}.setId(id);
        i${entity}.setActive(1);
        if (i${entity}Service.updateById(i${entity})){
            return CommonResult.successMsg("激活成功");
        }
        return CommonResult.failed("激活失败");
    }

    /**
     * active 字段 相当于激活一样 设置字段的有效性 active=0 无效 逻辑删除
    */
    @PutMapping("/del/{id}")
    public CommonResult loginDel(@PathVariable int id) {
        ${entity} i${entity} = new ${entity}();
        i${entity}.setId(id);
        i${entity}.setActive(0);
        if (i${entity}Service.updateById(i${entity})){
            return CommonResult.successMsg("设置失效成功");
        }
        return CommonResult.failed("设置失效失败");
    }

    /**
     * 批量设置 active=0
    */
    @PutMapping("/batchDel")
    public CommonResult LoginBatchDel(@RequestParam String ids) {
        ${entity} i${entity} = new ${entity}();
        i${entity}.setActive(0);
        String[] idList = ids.split(",");
        for (String id : idList) {
            i${entity}.setId(Integer.parseInt(id));
            i${entity}Service.updateById(i${entity});
        }
        return CommonResult.successMsg("批量失效成功");
    }

    /**
     * 在数据表中真正的删除一条记录
    */
    @DeleteMapping("/{id}")
    public CommonResult delById(@PathVariable int id) {
        if (i${entity}Service.removeById(id)){
            return CommonResult.successMsg("删除成功");
        }
        return CommonResult.failed("删除失败");
    }

}
</#if>

InitUtil

package com.neuedu.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 初始化一些查找信息
 */
public class InitUtil {
    /**
     * 初始化分页信息
     */
    public static void initPage(Map<String, Object> param) {
        if (StringUtils.isEmpty(param.get("page"))) {
            param.put("page", 1);
        }
        if (StringUtils.isEmpty(param.get("limit"))) {
            param.put("limit", 5);
        }
    }

    /**
     * 通过传入的字符串,然后在Map查找判断 如果存在则设置相似查找 是ADN 连接
     */
    public static void initLike(Map<String, Object> param, QueryWrapper wrapper, String ...str){
        for(String s:str){
            if(!StringUtils.isEmpty(param.get(s))){
                wrapper.like(s, param.get(s));
            }
        }
    }
    /**
     * 通过传入的字符串,然后在Map查找判断 如果存在则设置相等查找 是ADN 连接
     */
    public static void initEq(Map<String, Object> param,QueryWrapper wrapper, String ...str){
        for(String s:str){
            if(!StringUtils.isEmpty(param.get(s))){
                wrapper.eq(s, param.get(s));
            }
        }
    }
}

CommonResult

package com.neuedu.util;

import lombok.Data;

import java.io.Serializable;

@Data
public class CommonResult implements Serializable {
    private Integer code;
    private String message;
    private Object obj;

    private CommonResult(Integer code, String message, Object obj) {
        this.code = code;
        this.message = message;
        this.obj = obj;
    }

    public static CommonResult success(Object obj)
    {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),obj);
    }

    public static CommonResult success()
    {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),null);
    }

    public static CommonResult successMsg(String msg)
    {
        return new CommonResult(ResultCode.SUCCESS.getCode(),msg,null);
    }

    public static CommonResult failed()
    {
        return new CommonResult(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(),null);
    }


    public static CommonResult failed(String msg)
    {
        return new CommonResult(ResultCode.FAILED.getCode(),msg,null);
    }
}

ResultCode

import lombok.Getter;

@Getter
public enum  ResultCode {

    SUCCESS(200,"操作成功"),
    FAILED(500,"操作失败"),
    ;

    private Integer code;
    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

问题

  • idea 修改文件类型: 在File→Settings->File Types里进行配置
  • idea 运行main方法时,没找到字节码文件 删除idea生成的配置文件,然后pom右击选择reload project
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值