idea生成实体类自定义模板

最近在使用idea创建实体类的时候,不管是在persistence还是database panel中生成的实体类,都与个人所想要的实体类有一定的差距,例如想要添加swagger支持、默认实现序列化、设定id生成策略、设置注释模板等,所以手痒直接开敲,使用自定义的entity生成模板。PS:如果使用mybatis的话,可以下载一下mybatis插件(MyBatis plugin),更加有针对性生成对应的实体类、mapper xml等。

1、创建数据库连接,选择所使用的数据库

idea生成实体类自定义模板_第1张图片
设置数据库连接信息,并且test connection确定配置无误
idea生成实体类自定义模板_第2张图片

2、创建entity生成模板,打开idea的scripts directory

idea生成实体类自定义模板_第3张图片
创建属于自己的实体类生成模板,我这边命名为 Entity.groovy,代码奉上

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

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

packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)      : "Integer",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?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) }
}
/**
 * 创建对应的pojo Java文件
 * @param table
 * @param dir
 * @return
 */
def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields) }
}

/**
 * 实体类代码生成
 * @param out
 * @param className
 * @param fields
 * @return
 */
def generate(out, className, fields) {
    out.println "package $packageName"
    out.println ""
    out.println "import java.io.Serializable;"
    out.println ""
    out.println "public class $className  implements Serializable {"
    out.println ""
    out.println genSerialID()
    out.println ""
    fields.each() {
        if (it.annos != "") out.println "  ${it.annos}"
        out.println "  private ${it.type} ${it.name};"
    }
    out.println ""
    fields.each() {
        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 "}"
}
/**
 * 获取包名称
 * @param dir 实体类所在目录
 * @return
 */
def getPackageName(dir) {
    return dir.toString().replaceAll("/", ".").replaceAll("\\\\", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

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
        fields += [[
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           annos: ""]]
    }
}

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

static String genSerialID()
{
    return "  private static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;";
}


你可能感兴趣的:(IDEA,配置问题,实体类,idea生成实体类自定义模板)