idea生成实体类

2021年11月21日 阅读数:7
这篇文章主要向大家介绍idea生成实体类,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

一、点击View->Tool Windows->Databasejava

二、点击Datebase框的加号,DateSource,选择对应的数据源,配置对应信息,点击Test Connection测试连通性api

 

三、配置完成数据源后,选择须要生成实体的表,右键选择Script Extensions,Go To Script Directory,把脚本文件(GenerateMyPOJOs.groovy)放到Script目类app

 

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

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

typeMapping = [
        (~/(?i)number\(\d\)/)              : "int",
        (~/(?i)number/)              : "double",
        (~/(?i)int/)                      : "int",
        (~/(?i)long/)                      : "long",
        (~/(?i)float|double|decimal|real/): "double",
        (~/(?i)timestamp|datetime|date|time/)              : "LocalDateTime",
        (~/(?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)
    def file = new File(dir,className+".java")
    def packageName = dir.toString().replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
    def writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))

    writer.withPrintWriter { out -> generate(out, table, fields, packageName) }
}

def generate(out, table, fields, packageName) {
    def tableName = table.getName()
    def className = javaName(tableName, true)
    def tableComment = table.getComment()
    def hasPK = DasUtil.getPrimaryKey(table)!=null
    def hasDatetime = false
    fields.each() {hasDatetime=hasDatetime||it.type=="LocalDateTime"}

    out.println "package $packageName"
    out.println ""
    out.println "import javax.persistence.*;"
    if (hasPK) out.println "import java.time.LocalDateTime;"
    out.println "import org.hibernate.annotations.GenericGenerator;"
    out.println ""
    if (tableComment != "" && tableComment != null){
        out.println "/**"
        out.println " * ${tableComment}"
        out.println " */"
    }
    if (hasPK) out.println "@Entity"
    out.println "@Table(name = \"${tableName}\")"
    out.println "public class $className {"
    out.println ""
    fields.each() {
        out.println "    //${it.commoent} ${it.spec}"
        out.println "    private ${it.type} ${it.name};"
        out.println ""
    }
    fields.each() {
        out.println ""
        if (it.isId) out.println "    @Id"
        if (it.isId) out.println "    @GeneratedValue()"
        if (it.annos != "") out.println "    ${it.annos}"
        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 calcFields(table) {
    def primaryKey = DasUtil.getPrimaryKey(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()
        fields += [[
                           name    : javaName(col.getName(), false),
                           type    : typeStr,
                           commoent: col.getComment(),
                           spec:spec,
                           isId    : primaryKey != null && DasUtil.containsName(colName, primaryKey.getColumnsRef()),
                           annos   : "@Column(name = \"${colName}\")",
                   ]]
    }
}

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

  

再次右键须要转换的表,Script Extensions,选择GenerateMyPOJOs.groovy,选择对应目录,便可生成实体类测试

 

 

能够根据本身的须要修改groovy脚本,生成合适的实体类this