Mybatis-Plus代码生成器

Mybatis-Plus代码生成器,第1张

一、参考文档

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


二、导入依赖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>

三、创建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();
    }
}

四、自定义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

五、运行结果

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/758076.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-01
下一篇 2022-05-01

发表评论

登录后才能评论

评论列表(0条)

保存