idea database 生成bean,並且新增中文註釋
阿新 • • 發佈:2018-12-11
一、調出database視窗
view---Tool windows----databse
二、新增mysql的dataSource
三、填寫資料庫資訊,並且確定
四、選中表,去配置檔案
五、新增兩段程式碼,修改一段程式碼
實現Serializable介面,並且添加註釋
在檔案的最後新增一個方法,為了上面的程式碼呼叫
這時候如果直接生成,生成的bean註釋是亂碼,要再更改寫檔案的方法
六、修改完成的程式碼,可以直接複製
import com.intellij.database.model.DasTable import com.intellij.database.util.Case import com.intellij.database.util.DasUtil import java.io.* /* * Available context bindings: * SELECTION Iterable<DasObject> * PROJECT project * FILES files helper */ packageName = "com.youxia.lookvideo.pojo;" typeMapping = [ (~/(?i)int/) : "Long", (~/(?i)float|double|decimal|real/): "Double", (~/(?i)datetime|timestamp/) : "java.util.Date", (~/(?i)date/) : "java.util.Date", (~/(?i)time/) : "java.util.Date", (~/(?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) PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream( new File(dir, className + ".java")), "utf-8")) output.withPrintWriter { out -> generate(out, className, fields) } } def generate(out, className, fields) { out.println "package $packageName" out.println "import java.io.Serializable;" out.println "" out.println "public class $className implements Serializable{" out.println "" fields.each() { if (isNotEmpty(it.commoent)) { out.println "" out.println "\t/**" out.println "\t * ${it.commoent}" out.println "\t */" } 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), type : typeStr, commoent: col.getComment(), 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] } def isNotEmpty(content) { return content != null && content.toString().trim().length() > 0 }
T