Idea groovy表生成实体类带注释

1.点开datasourse,打开idea带的数据库工具,具体添加数据库连接,这里不描述。


image.png
  1. 这时点击会生成一个poji


    image.png

    这时生成的pojo中是不带中文注释的,需要自己配置,往下:
    3.根据图中的步骤走,找到groovy配置文件


    image.png

    image.png

    4.根据项目情况,自己定义规则
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.cscec;"
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Integer",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp|date|time/)    : "Date",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?i)number/)                          : "Integer",
        (~/(?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 com.baomidou.mybatisplus.annotation.IdType;"
    out.println "import com.baomidou.mybatisplus.annotation.KeySequence;"
    out.println "import com.baomidou.mybatisplus.annotation.TableId;"
    out.println "import com.cscec.epc.common.BaseOperationEntity;"
    out.println "import lombok.Data;"

    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 on " + new SimpleDateFormat("yyyy/MM/dd").format(new Date()) +"."
    out.println " */"
    out.println "@Data"
    out.println "@KeySequence(value = \"" + table.getName() + "_SEQ\")"
    out.println "public class $className extends BaseOperationEntity {"
    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 ""
    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   : ""
        ]
        if ("id".equals(Case.LOWER.apply(col.getName())))
            comm.annos = "\t@TableId(value = \"id\", type = IdType.INPUT)"
        fields += [comm]
    }
}

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

配置好后,重新回到步骤2生成,即可生成想要的带中文的实体啦~


image.png

你可能感兴趣的:(Idea groovy表生成实体类带注释)