idea软件自身提供了方法用于实体对象的生成,可借助此方法来进行无需单独安装插件。在DataBase窗口中点击要操作的表右键打开,可看到如下:
Generate POJOs.groovy文件提供了相关实体生成时展示的内容,我们可根据自身需求再进行调整,比如添加注释、注解、包等内容。
com.intellij.database.util.DasUtil包中会提供很多相关方法,可自行查看。
import com.intellij.database.model.DasTableimport com.intellij.database.util.Caseimport com.intellij.database.util.DasUtil/** Available context bindings:* SELECTION Iterable<DasObject>* PROJECTproject* FILES files helper*/packageName = "com.sample;"typeMapping = [(~/(?i)int/) : "long",(~/(?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 }.each { generate(it, dir) }}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 "\t/**"out.println "\t * @description"+table.getComment()out.println "\t * @author 杨洋"out.println "\t * @date "+new Timestamp(System.currentTimeMillis())out.println "\t */"out.println ""out.println "@Data"out.println "@Table(name = \""+table.getName()+"\")"out.println "public class $className {"out.println ""fields.each() {// 输出注释if (ment!="") {out.println "\t/**"out.println "\t * ${ment.toString()}"out.println "\t */"}//添加column注解if(it.isPkey){out.println " @Id"}if (it.annos != "") out.println " ${it.annos}"out.println " @Column(name = \"${it.filed}\")"out.println " private ${it.type} ${it.name};"}out.println ""fields.each() {out.println ""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 "}"}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() }.valuefields += [[name : javaName(col.getName(), false),type : typeStr,filed: col.getName(),//字段说明,此处采用utf-8无效依然会报错,在上面的输出流中修改 //(new String(col.getComment().getBytes("utf-8")))comment: col.getComment(), isPkey: DasUtil.isPrimary(col),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]}