IDEA Generate.POJOs.groovy生成实体类,这篇文章还教不会你?

IDEA通过Generate.POJOs.groovy映射数据库自动生成对应的Java实体类
具体逻辑不详细展示,可参考:
https://blog.csdn.net/qq_34371461/article/details/80571281

以下配置为映射逻辑:

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

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

packageName = "com.sample;"
typeMapping = [
        (~/(?i)int/)                         : "long",
        (~/(?i)float|double|decimal|real/)   : "double",
        // (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        // (~/(?i)date/)                     : "java.sql.Date",
        // (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)datetime|timestamp|date|time/): "Date",
        (~/(?i)/)                            : "String"
]

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)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    new File(dir, className + ".java").withPrintWriter("utf-8") { out -> generate(out, className, fields, table) }
}

// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import lombok.EqualsAndHashCode;"
    out.println "import lombok.Data;"
    // out.println "import java.util.Date;"

    out.println "import com.bocloud.entity.annotations.Column;"
    out.println "import com.bocloud.entity.annotations.PK;"
    out.println "import com.bocloud.entity.annotations.Table;"
    out.println "import com.bocloud.entity.bean.GenericEntity;"

    Set types = new HashSet()
    fields.each() {
        types.add(it.type)
    }
    if (types.contains("Date")) {
        out.println ""
        out.println "import java.util.Date;"
    }
    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }

    out.println ""
    out.println "/**"
    out.println " * @author jiaohongtao"
    out.println " * @version 1.0"
    out.println " * @since " + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
    out.println " */"
    out.println "@EqualsAndHashCode(callSuper = true)"
    out.println "@Data"
    out.println "@Table(\"" + table.getName() + "\")"
    out.println "public class $className extends GenericEntity {"
    out.println ""
    fields.each() {
        // 输出注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t/**"
            out.println "\t * ${it.commoent.toString()}"
            out.println "\t */"
        }

        if (it.annos != "") out.println "  ${it.annos}"
        out.println "\tprivate ${it.type} ${it.name};"
    }
    out.println ""
    // use Lombok
    // fields.each() {
    //   out.println ""
    //   out.println "  public ${it.type} get${it.name.capitalize()}() {"
    //   out.println "    return ${it.name};"
    //   out.println "  }"
    //   out.println ""
    //   out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
    //   out.println "    this.${it.name} = ${it.name};"
    //   out.println "  }"
    //   out.println ""
    // }
    out.println "}"
}

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

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   : "\t@Column(\"" + col.getName() + "\")"]
        if ("id".equals(Case.LOWER.apply(col.getName())))
            comm.annos = "\t@PK"
        fields += [comm]

        // fields += [[
        //            name : javaName(col.getName(), false),
        //            type : typeStr,
        //            annos: ""]]
    }
}

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]
}

参考:悲凉的秋风-https://blog.csdn.net/qq_34371461/article/details/80571281

你可能感兴趣的:(Java)