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名字
相关推荐
头发还在的女程序员1 天前
医院陪诊管理系统怎么选择?——2026 年选型避坑与架构参考
java·开发语言·陪诊系统·陪诊app·医院陪诊陪护
CodeStats1 天前
【Spring事务】Spring事务注解 @Transactional 完整体系:从 MySQL 隔离级别到 MyBatis 原理详解
java·spring·mybatis·事务·transactional
我命由我123451 天前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
都叫我大帅哥1 天前
从Python到Java:为什么企业级Agent最终会选择Java?
java·ai编程
wanderist.1 天前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
腻害兔1 天前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:IM 即时通讯模块,一个被低估的「全功能聊天系统」
java·前端·vue.js·产品经理·ai编程
心念枕惊1 天前
.NET CORE 授权进阶-角色、策略与动态权限实现
java·前端·.netcore
景同学1 天前
把 AI 用到线上运维:可行、有效,前提是喂足信息——一次 Full GC 排障实录
java·人工智能·后端
C++、Java和Python的菜鸟1 天前
第7章 后端Web实战(Tlias系统)
java
憧憬成为java架构高手的小白1 天前
黑马八股--spring框架学习
java·学习·spring