Lab 023

IntelliJ IDEA IU数据库脚本: 导出JPA+JDBC Entity(无Lombok)

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

packageName = "io.github.lab023.c86.spider.entity;"
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?i)datetime|ts/)              : "Timestamp",
        (~/(?i)date/)                     : "Date",
        (~/(?i)time/)                     : "Timestamp",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

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

def generate(table, out, className, fields) {
    out.println "package $packageName"
    out.println ""
    out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
    out.println "import com.fasterxml.jackson.annotation.JsonProperty;"
    out.println ""
    out.println "import javax.persistence.Column;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Id;"
    out.println "import javax.persistence.Table;"
    out.println "import javax.persistence.GeneratedValue;"
    out.println "import javax.persistence.GenerationType;"
    out.println "import java.io.Serializable;"
    out.println "import java.sql.Timestamp;"
    out.println "import java.sql.Date;"
    out.println "import java.sql.Time;"
    out.println ""
    out.println "@Entity"
    out.println "@Table(name = \"${table.getName()}\")"
    out.println "public class $className implements Serializable {"
    out.println "    public static final String tableName = \"${table.getName()}\";"
    out.println "    private static final long serialVersionUID = 1L;"
    out.println ""
    fields.each() {
        if (it.annos != "") out.println "  ${it.annos}"
        if (it.type == "Timestamp") out.println "    @JsonFormat(locale = \"zh\", timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")"
        if (it.type == "Date") out.println "    @JsonFormat(locale = \"zh\", timezone = \"GMT+8\", pattern = \"yyyy-MM-dd\")"
        out.println "    @JsonProperty(\"${toCamelCase(it.name)}\")"
        out.println "    @Column(name = \"${it.name}\")"
        out.println "    private ${it.type} ${toCamelCase(it.name)};"
    }
    out.println ""
    out.println constructNo(className, fields)
    out.println ""
    out.println construct(className, fields)
    out.println ""
    out.println constructAll(className, fields)
    out.println getAndSet(fields)
    out.println toString(fields)
    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
        def colName = col.getName() + ""

        // PK字段的开头必须是 idt_
        if (colName ==~ /(^idt$|^id$|^idt_.*)/) {
            fields += [[
                               name : colName,
                               type : typeStr,
                               annos: "  @Id" + (typeStr == "Long" ? "\n    @GeneratedValue(strategy = GenerationType.IDENTITY)" : "")]]
        } else {
            fields += [[
                               name : colName,
                               type : typeStr,
                               annos: ""]]
        }
    }
}

// 表名转类名
def javaName(str, capitalize) {
    def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("")
    capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

// 全字段构造函数
def constructAll(className, fields) {
    def inputArgs = ""
    def thisArgs = ""
    fields.each() {
        inputArgs += "${it.type} ${toCamelCase(it.name)}, "
        thisArgs += "        this.${toCamelCase(it.name)} = ${toCamelCase(it.name)};\n"
    }
    inputArgs = inputArgs.replaceAll('[,][ ]$', '')
    def ret = ""

    ret += "    public ${className}(${inputArgs}) {\n"
    ret += thisArgs
    ret += "    }"
    return ret
}

// 不含主键的构造函数
def constructNo(className, fields) {
    def ret = ""
    ret += "    public ${className}() {\n"
    ret += "    }"
    return ret
}

// 不含主键的构造函数
def construct(className, fields) {
    def inputArgs = ""
    def thisArgs = ""
    fields.each() {
        if (it.annos == "") {
            inputArgs += "${it.type} ${toCamelCase(it.name)}, "
            thisArgs += "        this.${toCamelCase(it.name)} = ${toCamelCase(it.name)};\n"
        }
    }
    inputArgs = inputArgs.replaceAll('[,][ ]$', '')
    def ret = ""

    ret += "    public ${className}(${inputArgs}) {\n"
    ret += thisArgs
    ret += "    }"
    return ret
}

// Getter and Setter
def getAndSet(fields) {
    def getStm = ""
    def setStm = ""
    fields.each() {
        getStm += "\n    public ${it.type} get${firstUpper(toCamelCase(it.name))}() {\n" +
                "        return ${toCamelCase(it.name)};\n" +
                "    }\n\n"
        setStm += "    public void set${firstUpper(toCamelCase(it.name))}(${it.type} ${toCamelCase(it.name)}) {\n" +
                "        this.${toCamelCase(it.name)} = ${toCamelCase(it.name)};\n" +
                "    }\n"
    }
    return getStm + setStm
}

// ToString
def toString(fields) {
    def stm = "    @Override\n" +
            "    public String toString() {\n" +
            "        return \"{\""
    fields.each() {
        stm += " + \" \\\"${toCamelCase(it.name)}\\\": \" + ${toCamelCase(it.name)} + \",\""
    }
    return stm + " + \"}\";\n    }"
}

// 驼峰命令
static String toCamelCase(String text, boolean capitalized = false) {
    text = text.replaceAll("(_)([A-Za-z0-9])", { Object[] it -> it[2].toUpperCase() })
    return capitalized ? capitalize(text) : text
}

// 蛇形命名
static String toSnakeCase(String text) {
    text.replaceAll(/([A-Z])/, /_$1/).toLowerCase().replaceAll(/^_/, '')
}

// 首字母大写
def firstUpper(str) {
    Case.UPPER.apply(str[0]) + str[1..-1]
}