idea默认代码生成脚本修改

修改了下idea自带的代码生成脚本,增加了脚本代码的注释,生成了controller,service,impl,mapper,里面都是空的,具体可以根据自己的代码习惯增加

代码生成脚本的使用可以看下使用 idea 生成实体类代码

修改后的脚本代码

java 复制代码
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import com.intellij.database.model.ObjectKind
import java.io.*
import java.text.SimpleDateFormat


/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
/**
 * 对应类型转换配置
 * 数据库类型:java类型
 */
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)  : "Integer",
        (~/(?i)int/)                         : "Long",
        (~/(?i)bool|bit/)                    : "Boolean",
        (~/(?i)float|double|decimal|real/)   : "Double",
        (~/(?i)datetime|timestamp|date|time/): "Date",
        (~/(?i)/)                            : "String"
]

/**
 * 程序入口
 */
FILES.chooseDirectoryAndSave("选择文件夹", "选择controller、domain,service,mapper的上级目录,生成的代码将会保存到对应文件夹。") {
    dir -> SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

/**
 * 代码生成
 * @param table 表的对象
 * @param dir 选择的文件夹路径
 */
def generate(table, dir) {
    String domainDir = "${dir}/domain"
    String domainClassName = javaName(table.getName(), true)
    String domainPackageName = getPackageName(domainDir)
    // 生成实体类
    // 这个utf8是解决乱码
    new File(domainDir, "${domainClassName}.java")
            .withPrintWriter("UTF-8") {
                out -> generateDomain(out, domainClassName, table, domainPackageName)
            }
    // 生成mapper
    String mapperDir = "${dir}/mapper"
    String mapperClassName = "${domainClassName}Mapper"
    String mapperPackageName = getPackageName(mapperDir)
    new File(mapperDir, "${mapperClassName}.java")
            .withPrintWriter("UTF-8") {
                out ->
                    generateMapper(out, mapperClassName, mapperPackageName,
                            domainClassName, domainPackageName)
            }
    // 生成service
    String serviceDir = "${dir}/service"
    String serviceClassName = "${domainClassName}Service"
    String servicePackageName = getPackageName(serviceDir)
    new File(serviceDir, "${serviceClassName}.java")
            .withPrintWriter("UTF-8") { out -> generateService(out, serviceClassName, servicePackageName) }

    // 生成serviceImpl
    String servicImplDir = "${serviceDir}/impl"
    String serviceImplClassName = "${serviceClassName}Impl"
    String serviceImplPackageName = getPackageName(servicImplDir)
    new File(servicImplDir, "${serviceImplClassName}.java")
            .withPrintWriter("UTF-8") {
                out ->
                    generateServiceImpl(out, serviceImplClassName, serviceImplPackageName,
                            serviceClassName, servicePackageName, mapperPackageName,
                            mapperClassName, domainClassName, domainPackageName)
            }

    // 生成Controller
    String controllerDir = "${dir}/controller"
    String controllerClassName = "${domainClassName}Controller"
    String controllerPackageName = getPackageName(controllerDir)
    new File(controllerDir, "${controllerClassName}.java")
            .withPrintWriter("UTF-8") {
                out ->
                    generateController(out, controllerClassName, controllerPackageName,
                            serviceImplClassName, serviceImplPackageName, serviceClassName,
                            servicePackageName, domainClassName, domainPackageName)
            }

}

/**
 * 文件夹路径转换为包名
 * @param dir 文件夹路径
 * @return 包名
 */
static String getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".")
            .replaceAll("^.*src(\\.main\\.java\\.)?", "")
}
/**
 * 生成实体类
 * @param out 输出流
 * @param className 类名
 * @param table 数据库表对象
 * @param dir 文件夹路径
 */
def generateDomain(out, className, table, domainPackageName) {
    def fields = calcFields(table)
    String tableName = table.getName();
    def comment = table.getComment();
    out.println "package $domainPackageName;"
    out.println ""
    out.println "import com.baomidou.mybatisplus.annotation.IdType;"
    out.println "import com.baomidou.mybatisplus.annotation.TableField;"
    out.println "import com.baomidou.mybatisplus.annotation.TableId;"
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println "import java.util.Date;"
    out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
    out.println "import java.io.Serializable;"
    out.println "import lombok.Data;"
    out.println "import lombok.AllArgsConstructor;"
    out.println "import lombok.Builder;"
    out.println "import lombok.NoArgsConstructor;"
    out.println ""
    out.println "/**"
    out.println "* $comment"
    out.println "* @author zjx"
    out.println "*/"
    out.println "@Data"
    out.println "@TableName(\"$tableName\")"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    out.println "@Builder"
    out.println "public class $className implements Serializable{"
    out.println ""
    out.println "\t@TableField(exist = false)"
    out.println genSerialID()
    out.println ""
    fields.each() {
        // 输出注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t/**"
            out.println "\t * ${it.commoent}"
            out.println "\t */"
        }
        if (it.type == "Date") {
            out.println "\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")"
        }
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "\tprivate ${it.type} ${it.name};"
    }
    out.println ""
    out.println "}"
}

/**
 * 生成mapper
 * @param out 输出流
 * @param mapperClassName mapper类名
 * @param mapperPackageName mapper包名
 * @param domainClassName 实体类类名
 * @param domainPackageName 实体类包名
 */
void generateMapper(out, mapperClassName, mapperPackageName, domainClassName,
                    domainPackageName) {
    out.println "package $mapperPackageName;"
    out.println ""
    out.println "import $domainPackageName.$domainClassName;"
    out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
    out.println "import org.apache.ibatis.annotations.Mapper;"
    out.println ""
    out.println "/**"
    out.println "* @author zjx"
    out.println "*/"
    out.println "@Mapper"
    out.println "public interface $mapperClassName extends BaseMapper<$domainClassName>{"
    out.println ""
    out.println "}"
}
/**
 * 生成service
 * @param out 输出流
 * @param serviceClassName service类名
 * @param servicePackageName service包名
 */
void generateService(out, serviceClassName, servicePackageName) {
    out.println "package $servicePackageName;"
    out.println ""
    out.println "/**"
    out.println "* @author zjx"
    out.println "*/"
    out.println "public interface $serviceClassName {"
    out.println ""
    out.println "}"
}
/**
 * 生成ServiceImpl
 * @param out 输出流
 * @param serviceImplClassName serviceImpl类名
 * @param serviceImplPackageName serviceImpl包名
 * @param serviceClassName service类名
 * @param service包名
 * @param mapperPackageName mapper类名
 * @param mapperClassName mapper包名
 * @param domainClassName 实体类类名
 * @param domainPackageName 实体类包名
 */
void generateServiceImpl(out, serviceImplClassName, serviceImplPackageName,
                         serviceClassName, servicePackageName, mapperPackageName,
                         mapperClassName, domainClassName, domainPackageName) {
    String lowerMapperClassName =
            mapperClassName.length() == 1 ? mapperClassName : mapperClassName[0].toLowerCase() + mapperClassName[1..-1];
    out.println "package $serviceImplPackageName;"
    out.println ""
    out.println "import $servicePackageName.$serviceClassName;"
    out.println "import $mapperPackageName.$mapperClassName;"
    out.println "import org.springframework.stereotype.Service;"
    out.println "import javax.annotation.Resource;"
    out.println ""
    out.println "/**"
    out.println "* @author zjx"
    out.println "*/"
    out.println "@Service"
    out.println "public class $serviceImplClassName implements $serviceClassName {"
    out.println "\t@Resource"
    out.println "\tprivate $mapperClassName $lowerMapperClassName;"
    out.println ""
    out.println "}"
}

/**
 *
 * 生成ServiceImpl
 * @param out 输出流
 * @param serviceImplClassName serviceImpl类名
 * @param serviceImplPackageName serviceImpl包名
 * @param serviceClassName service类名
 * @param service包名
 * @param controllerClassName controller类名
 * @param controllerPackageName controller包名
 * @param domainClassName 实体类类名
 * @param domainPackageName 实体类包名
 */
void generateController(out, controllerClassName, controllerPackageName,
                        serviceImplClassName, serviceImplPackageName, serviceClassName,
                        servicePackageName, domainClassName, domainPackageName){
    String lowerServiceClassName =
            serviceClassName.length() == 1 ? serviceClassName : serviceClassName[0].toLowerCase() + serviceClassName[1..-1];
    String lowerDomainClassName =
            domainClassName.length() == 1 ? domainClassName : domainClassName[0].toLowerCase() + domainClassName[1..-1];
    out.println "package $serviceImplPackageName;"
    out.println ""
    out.println "import $servicePackageName.$serviceClassName;"
    out.println "import javax.annotation.Resource;"
    out.println "import org.springframework.web.bind.annotation.RestController;"
    out.println "import org.springframework.web.bind.annotation.RequestMapping;"
    out.println ""
    out.println "/**"
    out.println "* @author zjx"
    out.println "*/"
    out.println "@RestController"
    out.println "@RequestMapping(\"/${lowerDomainClassName}\")"
    out.println "public class $controllerClassName {"
    out.println "\t@Resource"
    out.println "\tprivate $serviceClassName $lowerServiceClassName;"
    out.println ""
    out.println "}"
}

/**
 * 读取处理表的数据
 * @param table 表的对象
 * @return 表的数据
 */
def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())

        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        def comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
                annos   : ""]
        if ("主键".equals(col.getComment().toString()))
            comm.annos += "\t@TableId(type = IdType.AUTO)"
        fields += [comm]
    }
}

/**
 * 表名转换为类名
 * @param tableName 表名
 * @param capitalize 是否将首字母转大写
 * @return 转换后的类名
 */
String javaName(tableName, capitalize) {
    String s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(tableName)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

static def isNotEmpty(content) {
    return content != null && content.toString().trim().length() > 0
}

/**
 * 生成serialVersionUID
 */
static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}
相关推荐
齐 飞24 分钟前
MongoDB笔记01-概念与安装
前端·数据库·笔记·后端·mongodb
云空25 分钟前
《Python 与 SQLite:强大的数据库组合》
数据库·python·sqlite
暮毅29 分钟前
10.Node.js连接MongoDb
数据库·mongodb·node.js
狂放不羁霸32 分钟前
idea | 搭建 SpringBoot 项目之配置 Maven
spring boot·maven·intellij-idea
wowocpp33 分钟前
ubuntu 22.04 server 格式化 磁盘 为 ext4 并 自动挂载 LTS
服务器·数据库·ubuntu
九圣残炎33 分钟前
【从零开始的LeetCode-算法】1456. 定长子串中元音的最大数目
java·算法·leetcode
wclass-zhengge35 分钟前
Netty篇(入门编程)
java·linux·服务器
成富1 小时前
文本转SQL(Text-to-SQL),场景介绍与 Spring AI 实现
数据库·人工智能·sql·spring·oracle
songqq271 小时前
SQL题:使用hive查询各类型专利top 10申请人,以及对应的专利申请数
数据库·sql
计算机学长felix1 小时前
基于SpringBoot的“校园交友网站”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·毕业设计·交友