Generate POJOs.groocvy
文件在 C:\Users\admin\AppData\Roaming\JetBrains\IntelliJIdea2020.2\extensions\com.intellij.database\schema
目录下。
也可以在IDEA的 Scratches and Consoles
Generate POJOs.groocvy脚本解析:
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.example.springcloud.bo;" //设置实体包名
typeMapping = [ //数据库字段对应java类型
(~/(?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) }
}
def generate(out, className, fields) { //开始拼接代码
out.println "package $packageName"
out.println "import lombok.Data;" //需要导入的
out.println ""
out.println ""
out.println "@Data" //注解
out.println "public class $className {"
out.println ""
fields.each() { //遍历字段属性
if (it.annos != "") out.println " ${it.annos}"
out.println " private ${it.type} ${it.name};"
}
out.println ""
// fields.each() {//遍历get、set方法
// 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() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
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]
}