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名字
相关推荐
古法老登瞎折腾6 小时前
大数据智能运维实战(十一):运维 MCP 的工程化——权限、限流、审计与错误处理
java·大数据·运维·spring ai·mcp
智能运维指南7 小时前
研制过程“两张皮“怎么破:研制一体化支撑平台的定位、能力边界与落地前提
java·前端·人工智能·嘉为蓝鲸
yz_aiks8 小时前
Spring AI 2.1 ChatMemory 已过时用什么替代:迁移到 Session Memory 实战(JDBC 存储与会话压缩)
java·spring boot·大模型·ai agent·spring ai
金銀銅鐵8 小时前
[Java] 用 GUI 展示 EnumMap 增删键值对时的内部变化
java·后端·ai编程
学长毕设8 小时前
基于SpringBoot的上门洗车服务系统设计与实现
java·spring boot·后端
jason成都8 小时前
RTKLIB-Java 多基线联合RTK:FIX率从0%到91.5%的三层根因修复
java·gnss·rtklib·rtklib_java
鱼宵9 小时前
Stream 终端操作一次讲透:collect、count、reduce 怎么选
java·stream·终端操作
白山编程大哥9 小时前
Java 后端如何优雅地把 List 集合返回给前端
java·前端·list
Linux运维技术栈9 小时前
CVE-2026-91403 高危漏洞修复:Rocky Linux 9 多版本 JDK 环境清理实操
java·linux·运维
On The Road :9 小时前
Java 多线程详解:从入门到线程安全
java·python·安全