根据表生成实体

一个小的脚本,用来根据表生成对应的实体,要把他放到idea中

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import com.intellij.psi.codeStyle.NameUtil

import java.text.SimpleDateFormat

def calcFields(table) {
    def typeMapping = [
            (~/(?i)int|tinyint/)                 : "Integer",
            (~/(?i)bigint/)                      : "Long",
            (~/(?i)float|double|decimal/)        : "Double",
            (~/(?i)date|datetime|time|timestamp/): "Date",
            (~/(?i)/)                            : "String"
    ]
    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
        fields += [[
                           name   : javaName(col.getName(), false),
                           type   : typeStr,
                           comment: col.getComment()
                   ]]
    }
}

def javaName(str, capitalize) {
    def s = 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]
}

def static getPackageName(dir) {
    dir.replaceAll("/", ".").replaceAll("^.*src.(main.java.)?", "") + ";"
}

def generate(table, dir) {
    def createDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date())
    def className = javaName(table.getName(), true)
    def tableName = table.getName()
    def tableComment = table.getComment()
    def fields = calcFields(table)
    def packageName = getPackageName("$dir")
    new File(dir, className + ".java")
            .withPrintWriter("UTF-8") { out -> generate(out, createDate, packageName, tableName, tableComment, className, fields) }
}

def generate(file, createDate, packageName, tableName, tableComment, className, fields) {
    file.println "package $packageName"
    file.println ""
    file.println "import com.baomidou.mybatisplus.annotation.TableName;"
    file.println "import com.csign.win.web.dao.BaseEntity;"
    file.println "import lombok.Getter;"
    file.println "import lombok.Setter;"
    file.println "import lombok.experimental.Accessors;"
    for (it in fields) {
        if (it.type == "Date" && it.name != "createTime" && it.name != "updateTime") {
            file.println "import java.util.Date;"
            break
        }
    }
    file.println ""
    file.println "/**"
    if (tableComment != null && tableComment != "") {
        file.println " * $tableComment"
    }
    file.println " * @author Sunry"
    file.println " * @since $createDate"
    file.println " */"
    file.println "@Getter"
    file.println "@Setter"
    file.println "@TableName(\"$tableName\")"
    file.println "@Accessors(chain = true)"
    file.println "public class $className extends BaseEntity<$className> {"
    file.println ""
    fields.each() {
        if (it.name == "id" || it.name == "delFlag" || it.name == "createTime" || it.name == "updateTime"){
            return
        }
        if (it.comment != null && it.comment != "") {
            file.println "    /**"
            file.println "     * ${it.comment}"
            file.println "     */"
        }
        if (it.name == "id"){
            file.println "    @TableId(type = IdType.AUTO)"
        }
        file.println "    private ${it.type} ${it.name};"
        file.println ""
    }
    file.println "}"
}

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

用idea自带的工具,连接到MySQL

选择要生成的表

最后选择生成后的位置!

上一篇
评论
说点什么吧?

发表评论

取消回复
  最新文章
  热门标签