import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.text.SimpleDateFormat
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.flower8.model;"
typeMapping = [
(~/(?i)int/) : "long",
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime|timestamp|time/) : "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).substring(2)
def fields = calcFields(table)
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter {out -> generate(out, className, fields,table)}
}
def generate(out, className, fields, table) {
out.println "package $packageName"
out.println "import lombok.Data;"
Set types = new HashSet()
String comm = "";
fields.each() {
types.add(it.type)
String str = it.tableCommoent.toString()
comm = str.substring(0,str.length()-1) +new String("的实体类".getBytes("gbk"),"utf-8")
}
if (types.contains("Date")) {
out.println "import java.util.Date;"
}
out.println "/**\n" +
" * @Description $comm \n" +
" * @Author tanglin\n" +
" * @Date "+ new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date()) + " \n" +
" * @Version 1.0\n" +
" */"
out.println ""
out.println "@Data"
out.println "public class $className extends BaseEntity<Long>{"
out.println ""
fields.each() {
if(it.name != "id" && it.name != "createTime" && it.name != "modifyTime"){
if (isNotEmpty(it.commoent)) out.println " //${it.commoent.toString()}"
out.println " private ${it.type} ${it.name};"
}
}
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),
colName : col.getName(),
type : typeStr,
commoent: col.getComment(),
tableCommoent: table.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
}