idea配置SpringBoot+MybatisPlus的Controller模板,一键生成Controller

本质是idea使用velocity生成代码

1、介绍一下

我用的MybatisX-Generator生成了entity和service等,但是他没有controller,还得自己创建好麻烦,于是写了模板。

我的格式(以t_user_info表为例):

  • com.xx.entity.UserInfoEntity
  • com.xx.service.UserInfoService

我想在com.xx.controller中输入UserInfoController,让他给我创建基本的接口,且自动引入service和entity

接口返回类型为R,代码放下面。

2、配置模板

打开idea中文件 - 设置 - 编辑器 - 文件和代码模板

在编辑区输入代码

java 复制代码
package ${PACKAGE_NAME};
#set($ch = "")
#set($first = true)
#set($EntityName = $NAME.replaceAll("Controller", ""))
#foreach($ch in $EntityName.toCharArray())
    #set($ch = $ch + "")
    #if($ch == $ch.toUpperCase())
        #if($first)
            #set($entityName = $ch.toLowerCase())
            #set($entity_name = $ch.toLowerCase())
            #set($first = false)
        #else
            #set($entityName = $entityName + $ch)
            #set($entity_name = $entity_name + "_" + $ch.toLowerCase())
        #end
    #else
        #set($entity_name = $entity_name + $ch)
        #set($entityName = $entityName + $ch)
    #end
#end
#set($PARENT_PACKAGE = "")
#set($lastDotIndex = $PACKAGE_NAME.lastIndexOf("."))
#if($lastDotIndex > 0)
    #set($PARENT_PACKAGE = $PACKAGE_NAME.substring(0, $lastDotIndex))
#else
    #set($PARENT_PACKAGE = $PACKAGE_NAME)
#end


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import ${PARENT_PACKAGE}.service.${EntityName}Service;
import ${PARENT_PACKAGE}.entity.${EntityName}Entity;
import ${PARENT_PACKAGE}.util.R;
import org.springframework.web.bind.annotation.*;

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


/**
 * @author ${USER}
 * @description 针对表【t_${entity_name}】的数据库操作Controller实现
 * @createDate ${TIME}
 */
@Slf4j
@RestController
@RequestMapping("/${entity_name}")
public class ${EntityName}Controller {

    @Resource
    private ${EntityName}Service ${entityName}Service;

    /**
     * 新增或更新
     */
    @PostMapping("/save")
    public R save(@RequestBody ${EntityName}Entity ${entityName}){
        log.info("${entityName}: {}", JSON.toJSONString(${entityName}));
        if (${entityName}.getId() == null) {
            boolean flag = ${entityName}Service.save(${entityName});
            return flag ? R.ok() : R.error("新增失败");
        } else {
            ${entityName}.setUpdateTime(new Date());
            boolean flag = ${entityName}Service.updateById(${entityName});
            return flag ? R.ok() : R.error("更新失败");
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id){
        if (id == null) {
            return R.error("删除失败");
        }
        boolean flag = ${entityName}Service.removeById(id);
        return flag ? R.ok() : R.error("删除失败");
    }

    /**
     * 查询
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        if (id == null) {
            return R.error("查询失败");
        }
        ${EntityName}Entity ${entityName} = ${entityName}Service.getById(id);
        return R.ok().data(${entityName});
    }

    /**
     * 分页查询
     */
    @PostMapping("/list")
    public R list(@RequestParam(name = "current", defaultValue = "1") int current,
                  @RequestParam(name = "size", defaultValue = "10") int size) {
        log.info("current: {}, size: {}", current, size);
        Page<${EntityName}Entity> page = new Page<>(current, size);
        ${entityName}Service.page(page);
        return R.ok().data(page);
    }

}

其中,我的R放在com.xx.util下,代码如下

java 复制代码
package com.xx.util;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;

@Data
@Accessors(chain = true)
public class R {

    private Integer code;

    private String message;

    private Object data;

    public R code(Integer code) {
        this.code = code;
        return this;
    }

    public R message(String message) {
        this.message = message;
        return this;
    }

    public R data(Map<String, Object> data) {
        this.data = data;
        return this;
    }

    public R data(Object data) {
        this.data = data;
        return this;
    }

    public R data(String key, Object value) {
        ((Map<String, Object>) this.data).put(key, value);
        return this;
    }

    private R() {
        this.data = new HashMap<>();
    }

    public static R error() {
        return new R().code(500).message("ERROR");
    }

    public static R error(int code) {
        return new R().code(code).message("ERROR");
    }

    public static R error(String message) {
        return new R().message(message);
    }

    public static R ok() {
        return new R().code(200).message("SUCCESS");
    }
}

3、使用

  • 在controller包下右键,新建 - Java类
  • 选择Controller,输入Controller名字
相关推荐
杨杨杨大侠5 小时前
都能接模型、RAG 和 MCP,Java Agent 框架到底差在哪?
java
凤山老林5 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
Thinker QAQ6 小时前
并发编程(九):BlockingQueue 与 Channel——语言层的原子性、可见性与有序性
java·python·go·并发编程·channel·blockingqueue·message passing
霸道流氓气质7 小时前
RAG 可观测性与生产监控实战:四层遥测模型、五大仪表盘与 OpenTelemetry 全链路追踪的 Java 生产级实现
java·人工智能·python
AOI小白新手上路7 小时前
autodl常用的tar 打包下载(数据集)命令手册:逐段拆解与套用模板
java·大数据·数据库
dishugj9 小时前
系统架构风险点、敏感点和权衡点的概念和区分
java·开发语言
苜蓿muxu9 小时前
常用代码命名规范
java
马优晨9 小时前
JAVA 中 VO 实体类是什么意思,为什么要做这个
java·开发语言·状态模式·java vo·java vo是什么
Baron X10 小时前
Eclipse Temurin 21 (JRE) Alpine 镜像获取、离线导入与推送操作
java·docker·eclipse·temurin