使用idea的groovy脚本自动创建MybatisPlus的实体

使用idea的groovy脚本自动创建MybatisPlus的实体

  1. 选中数据库的表;
  2. 右击选择Scripted Extension中的Go to scripts diretory;
  3. 新建一个文件,名称为:MybatisPlusGenerate POJOs.groovy;
  4. 复制粘贴如下内容;
  5. 选中数据库中需要新建entity的表;
  6. 右击选中Scripted Extension中的MybatisPlusGenerate POJOs.groovy执行;
  7. 在指定目录下生成驼峰命名的实体对象;
  8. 需要修改生成内容的,可以看看脚本内容,进行修改。
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.time.LocalDate

/*
 * Available context bindings:
 * SELECTION Iterable<DasObject>
 * PROJECT  project
 * FILES  files helper
 */

// 此处指定包路径,路径需要自行维护;
packageName = "com.cyneck.web.entity;"

// 此处指定对应的类型映射,可按需修改,目前tinyint如果要映射到自定义枚举类型,只能手动修改
typeMapping = [
        (~/(?i)bigint/)                         : "Long",
        (~/(?i)smallint|mediumint|tinyint|int/) : "Integer",
        (~/(?i)bool|bit/)                       : "Boolean",
        (~/(?i)float|double|decimal|real/)      : "BigDecimal",
        (~/(?i)time|datetime|timestamp/)        : "LocalDateTime",
        (~/(?i)date/)                           : "LocalDate",
        (~/(?i)blob|mediumblob|binary|bfile|clob|raw|image/): "Byte[]",
        (~/(?i)text|mediumtext/)                : "String",
        (~/(?i)/)                               : "String"
]

// 上面用到类和它的导入路径的之间的映射
importMap = [
        "BigDecimal" : "java.math.BigDecimal",
        "LocalDate" : "java.time.LocalDate",
        "LocalDateTime": "java.time.LocalDateTime",
]

// 导入路径列表,下面引用的时候会去重,也可以直接声明成一个 HashSet
importList = []

// 弹出选择文件的对话框
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true) + "Entity"
    def fields = calcFields(table)
    new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "utf-8")).withPrintWriter { out -> generate(out, className, fields, table) }
}

// 从这里开始,拼实体类的具体逻辑代码
def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    // 引入所需的包
    out.println "import lombok.Data;"
    out.println "import lombok.EqualsAndHashCode;"
    out.println "import lombok.experimental.Accessors;"
    out.println "import com.baomidou.mybatisplus.annotation.*;"
    out.println "import java.io.Serializable;"
    // 去重后导入列表
    importList.unique().each() { pkg ->
        out.println "import " + pkg + ";"
    }
    out.println ""
    // 添加类注释
    out.println "/**"
    // 如果添加了表注释,会加到类注释上
    if (isNotEmpty(table.getComment())) {
        out.println " * " + table.getComment()
    }
    out.println " *"
    out.println " * @author Eric.Lee"
    out.println " * @since " + LocalDate.now()
    out.println " */"
    // 添加类注解
    out.println "@Data"
    out.println "@EqualsAndHashCode(callSuper = false)"
    out.println "@Accessors(chain = true)"
    out.println "@TableName(\"${table.getName()}\")"
    out.println "public class $className implements Serializable {"
    out.println ""
    out.println genSerialID()
    boolean isId = true
    // 遍历字段,按下面的规则生成
    fields.each() {
        // 输出注释
        if (isNotEmpty(it.comment)) {
            out.println "\t/**"
            out.println "\t * ${it.comment}"
            out.println "\t */"
        }
        // 这边默认第一个字段为主键,实际情况大多数如此,遇到特殊情况可能需要手动修改
        if (isId) {
            out.println "\t@TableId(type = IdType.AUTO)"
            isId = false
        }
        if ((it.annos + "").indexOf("[@Id]") >= 0) out.println "\t@Id"

        if (it.annos != "") out.println " ${it.annos.replace("[@Id]", "")}"

        out.println "\tprivate ${it.type} ${it.name};"
        out.println ""
    }
    out.println ""
    out.println "}"
}

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
        if (importMap.containsKey(typeStr)) {
            importList.add(importMap.get(typeStr))
        }
        fields += [[
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           comment: col.getComment(),
                           annos : "\t@TableField(\"" + col.getName() + "\")"
                   ]]
    }
}

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

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

static String genSerialID() {
    return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"
}
posted @ 2021-01-09 16:57  Eric小星  阅读(1050)  评论(0编辑  收藏  举报