idea数据库表生成实体类

 

先说一下实现的功能:根据数据库,生成实体类.

生成的实体类的格式可参看下图:

idea数据库表生成实体类_第1张图片

生成的实体类中加入的注解有

       @Table注解,

        无getset方法.加入了lombok的@DATA ,@Slf4j注解.

       支持@ID注解.当字段名为id时.

       如果数据库表中字段通过comment设置了备注,那么类中字段显示相应注释.

具体实现,请先参考博文

Intellij IDEA 通过数据库表生成带注解的实体类详细步骤

参考博文中写的很详细.这里主要是做了改造,改造如下

1.参考博文中生成的类是gbk格式的,一般idea都是utf-8格式.还得一个个改编码很麻烦.

2.加入了lombok注解.使用lombok更加优雅方便.

3.文中生成的类文件中,@ID没有换行.

遗留问题:

  只能通过字段名是否为"id"来判断主键,去添加@ID注解..希望实现的同学可以分享出来.

 

最后,贴上修改的Generate.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

import java.sql.Date


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

packageName = "com.mm.pojo"//写你的实体类包名

typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Long",
        (~/(?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)/)                                : "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 = javaClassName(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 javax.persistence.Column;"
    out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"
    out.println "import java.io.Serializable;"
    out.println "import javax.persistence.Id;"
    out.println "import lombok.Data;"
    out.println "import lombok.extern.slf4j.Slf4j;"

    Set types = new HashSet()

    fields.each() {
        types.add(it.type)
    }

    if (types.contains("Date")) {
        out.println "import java.util.Date;"
    }

    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }
    out.println ""
    out.println "/**\n" +
            " * generated by Generate POJOs.groovy \n" +
            " * 

Date: "+new java.util.Date().toString()+".

\n" + " *\n" + " * @author \n" + " */" out.println "" out.println("@Entity") out.println("@Data") out.println("@Slf4j") out.println "@Table ( name =\""+table.getName() +"\" )" out.println "public class $className implements Serializable {" out.println "" out.println "" out.println genSerialID() out.println "" fields.each() { out.println "" // 输出注释 if (isNotEmpty(it.commoent)) { out.println "\t/**" out.println "\t * ${it.commoent}" out.println "\t */" } if (it.annos != "") out.println " ${it.annos}" // 输出成员变量 out.println "\tprivate ${it.type} ${it.name};" } // 输出get/set方法 // fields.each() { // out.println "" // out.println "\tpublic ${it.type} get${it.name.capitalize()}() {" // out.println "\t\treturn this.${it.name};" // out.println "\t}" // out.println "" // // out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {" // out.println "\t\tthis.${it.name} = ${it.name};" // out.println "\t}" // } out.println "" out.println "}" } 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 : changeStyle (javaName(col.getName(), false) ,true), type : typeStr, commoent: col.getComment(), annos: ("id".equals(Case.LOWER.apply(col.getName()))?"\t@Id\r\n":"")+"\t@Column(name = \""+col.getName()+"\" )"] fields += [comm] } } // 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T, // 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可) def javaClassName(str, capitalize) { def s = str.split(/[^\p{Alnum}]/).collect { def s = Case.LOWER.apply(it).capitalize() }.join("") // 去除开头的T http://developer.51cto.com/art/200906/129168.htm // s = s[1..s.size() - 1] capitalize ? s : Case.LOWER.apply(s[0]) + s[1..-1] } def javaName(str, capitalize) { def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() } .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_") capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1] } def isNotEmpty(content) { return content != null && content.toString().trim().length() > 0 } static String changeStyle(String str, boolean toCamel){ if(!str || str.size() <= 1) return str if(toCamel){ String r = str.toLowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('') return r[0].toLowerCase() + r[1..-1] }else{ str = str[0].toLowerCase() + str[1..-1] return str.collect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('') } } static String genSerialID() { return "\tprivate static final long serialVersionUID = "+Math.abs(new Random().nextLong())+"L;"; }

 

你可能感兴趣的:(理念使用)