Mybatis-Plus代码生成器

🎈 1 参考文档

代码生成器(新) | Mybatis-Plus

Mybatis-Plus自动生成代码,自定义Controller | 程序员青戈-CSDN


🚀2 导入依赖pom.xml

<!-- mybatis-plus代码生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<!-- velocity-engine-core模板 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

🚀3 创建CodeGenerator工具类

查看代码生成器配置新配置。

//mp代码生成器
public class CodeGenerator {
    private static String url = "jdbc:mysql://localhost:3306/ns?serverTimezone=GMT%2B8";

    private static String username = "root";

    private static String password = "011023";

    private static void generator() {
        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    builder.author("hyc") // 设置作者
//                            .fileOverride() // 覆盖已生成文件
                            .outputDir("C:\\Users\\14248\\IdeaProjects\\nsms\\src\\main\\java\\"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.hyc.nsms") // 设置父包名
                            .moduleName(null) // 设置父包模块名 无
                            .entity("model.entity")

                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "C:\\Users\\14248\\IdeaProjects\\nsms\\src\\main\\java\\com\\hyc\\nsms\\mapper\\xml\\")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.entityBuilder().enableLombok();
                    builder.mapperBuilder().enableMapperAnnotation().build();
                    builder.controllerBuilder().enableHyphenStyle()  // 开启驼峰转连字符
                            .enableRestStyle(); // 开启生成@RestController 控制器
                    builder.addInclude("role") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }

    public static void main(String[] args) {
        generator();
    }
}

🚀4 自定义Controller模板

找到controller.java.vm文件。

在这里插入图片描述

复制到resources下的templates文件夹中。

在这里插入图片描述

改成自己需要的,以下是我的模板:

package ${package.Controller};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyc.nsms.model.result.Result;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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


#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

#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

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

    //查询${entity}表所有信息
    @GetMapping("findAll${entity}")
    public Result findAll${entity}() {
        //调用service的方法
        List<${entity}> list = ${table.entityPath}Service.list();
        return Result.ok(list);
     }

    //根据id获取${entity}
    @GetMapping("get${entity}ById/{id}")
    public Result get${entity}ById(@PathVariable Integer id) {
        ${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);
        return Result.ok(${table.entityPath});
    }

    //条件查询带分页
    @PostMapping("findPage${entity}/{current}/{limit}")
    public Result findPage${entity}(@PathVariable Integer current, @PathVariable Integer limit, @RequestBody(required = false) ${entity} ${table.entityPath}) {
        //创建page对象,传递当前页,每页记录数
        Page<${entity}> page = new Page<>(current, limit);
        //构建条件
        QueryWrapper<${entity}> wrapper = new QueryWrapper<>();

        String ${table.entityPath}Name = ${table.entityPath}.get${entity}Name();//${entity}名称

        if (!StringUtils.isEmpty(${table.entityPath}Name)) {
            wrapper.like("${table.entityPath}_name", ${table.entityPath}Name);
        }

        //调用方法实现分页查询
        Page<${entity}> ${entity}Page = ${table.entityPath}Service.page(page, wrapper);
        //返回结果
        return Result.ok(${entity}Page);
     }

    //添加${entity}
    @PostMapping("save${entity}")
    public Result save${entity}(@RequestBody ${entity} ${table.entityPath}) {
        //调用service
        boolean save = ${table.entityPath}Service.save(${table.entityPath});
        if (save) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //修改${entity}信息
    @PostMapping("update${entity}")
    public Result update${entity}(@RequestBody ${entity} ${table.entityPath}) {
        boolean flag = ${table.entityPath}Service.updateById(${table.entityPath});
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //删除${entity}
    @DeleteMapping("{id}")
    public Result remove${entity}(@PathVariable Integer id) {
        boolean flag = ${table.entityPath}Service.removeById(id);
        if (flag) {
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    //批量删除${entity}
    @DeleteMapping("batchRemove")
    public Result batchRemoveHospitalSet(@RequestBody List<Integer> idList) {
        ${table.entityPath}Service.removeByIds(idList);
        return Result.ok();
    }
}

#end

📋 5 运行结果

在CodeGenerator工具类中的test或者main下直接运行。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值