IDEA导出数据库对应的实体配置

  笔者时常因为各种原因重装IDEA软件,导致有些配置找不到,或者忘记如何进行配置的。本次是自我配置(结合AI提示)编写了一个比较完整的 .groovy 文件。也可能因为使用的规则不同,请结合自己的需求进行修改.。

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import com.intellij.database.model.ObjectKind
import java.time.LocalDate
import java.time.format.DateTimeFormatter

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

packageName = "com.wjin.domain;"
typeMapping = [
        // 数值类型
        (~/(?i)tinyint/)            : "Byte",
        (~/(?i)smallint/)           : "Short",
        (~/(?i)int|integer/)        : "Integer",
        (~/(?i)bigint/)             : "Long",
        (~/(?i)decimal|numeric/)    : "BigDecimal",
        (~/(?i)real|float/)         : "Float",
        (~/(?i)double/)             : "Double",
        // 字符串类型
        (~/(?i)char|varchar|text|longtext|mediumtext|tinytext/) : "String",
        // 日期时间类型
        (~/(?i)date/)               : "Date",
        (~/(?i)time/)               : "Date",
        (~/(?i)datetime|timestamp/) : "Date",
        // 其他特殊类型
        (~/(?i)bit/)                : "Boolean",
        (~/(?i)bool|boolean/)       : "Boolean",
        (~/(?i)blob|binary|varbinary|longblob|mediumblob|tinyblob/) : "byte[]",
        (~/(?i)year/)               : "Integer",
        // 默认类型
        (~/(?i).*/)                 : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    def tables = SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }
    def totalTables = tables.size()
    def processedCount = 0

    tables.each { table ->
        try {
            def className = javaName(table.getName(), true)
            def fields = calcFields(table)
            def file = new File(dir, className + ".java")

            // 检查文件是否已存在
            if (file.exists()) {
                // 这里可以根据需要添加用户确认逻辑
                println "Warning: File ${file.name} already exists and will be overwritten"
            }

            // 检查目录写入权限
            if (!dir.canWrite()) {
                throw new IOException("Cannot write to directory: ${dir.absolutePath}")
            }

            // 使用UTF-8编码写入文件
            file.withPrintWriter("UTF-8") { out ->
                generate(out, className, fields, table)
            }

            processedCount++
            println "Generated: ${file.name} (${processedCount}/${totalTables})"

        } catch (Exception e) {
            println "Error processing table ${table.getName()}: ${e.message}"
            // 可以选择继续处理其他表或停止执行
        }
    }
}

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

def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println ""
    out.println "/**"
    def tableComment = table.getComment() ?: className
    // 确保注释正确编码
    out.println " * @Desc: ${tableComment.toString()}"
    out.println " * @Author: w_jin"
    // 使用更可靠的日期格式化方法
    def currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
    out.println " * @Date ${currentDate}"
    out.println " */"
    out.println "public class $className {"
    out.println ""
    fields.each() {
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "    /**"
        def fieldComment = it.comment ?: it.name
        out.println "     * ${fieldComment.toString()}"
        out.println "     */"
        out.println "  private ${it.type} ${it.name};"
    }
    out.println ""

    fields.each() {
        out.println ""
        out.println "   /**"
        def fieldComment = it.comment ?: it.name
        out.println "    * 获取${fieldComment.toString()}"
        // 对Date类型使用特殊处理
        if (it.type == "Date") {
            out.println "    * @return ${it.name} ${fieldComment.toString()}"
            out.println "    */"
            out.println "  public ${it.type} get${it.name.capitalize()}() {"
            out.println "    return ${it.name} != null ? (Date) ${it.name}.clone() : null;"
            out.println "  }"
        } else {
            out.println "    * @return ${it.name} ${fieldComment.toString()}"
            out.println "    */"
            out.println "  public ${it.type} get${it.name.capitalize()}() {"
            out.println "    return ${it.name};"
            out.println "  }"
        }
        out.println ""
        out.println "   /**"
        out.println "    * 设置${fieldComment.toString()}"
        // 对Date类型使用特殊处理
        if (it.type == "Date") {
            out.println "    * @param ${it.name} ${fieldComment.toString()}"
            out.println "    */"
            out.println "  public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
            out.println "    this.${it.name} = ${it.name} != null ? (Date) ${it.name}.clone() : null;"
            out.println "  }"
        } else {
            out.println "    * @param ${it.name} ${fieldComment.toString()}"
            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) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDasType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           comment: col.getComment(),
                           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]
}

posted @ 2025-07-28 13:54  奋斗中de小伙有潜力  阅读(14)  评论(0)    收藏  举报