(SpringBoot-Jpa)使用Idea資料庫自動指令碼Generate POJOS生成 Entity物件,
阿新 • • 發佈:2019-02-04
- 因:使用SpringBoot -jpa,需要手動配置Entity
- 但是如果你的表中有很多屬性,或者有很多表怎麼辦?? 每個手動寫? 還是用mybatis。寫mapper???
- 解決:使用idea自動工具
- 使用工具可以生成pojo物件,但是缺少了註解:
- 手動修改李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 /* * Available context bindings: * SELECTION Iterable<DasObject> * PROJECT project * FILES files helper */ packageName = "com.inyu.entity;" 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 && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) } } def generate(table, dir) { def className = javaName(table.getName(), true) def fields = calcFields(table) new File(dir, className + ".java").withPrintWriter { out -> generate(out,table, className, fields) } } def generate(out,table, className, fields) { def tableName = table.getName(); out.println "package $packageName" out.println "" out.println "" 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() { 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), colum: col.getName(), type : typeStr, annos: ""]] } } 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] }