Instantly share code, notes, and snippets.

Embed
What would you like to do?
DatabaseウィンドウからDoma2のエンティティテンプレートを生成するやつ
import com.intellij.database.model.DasTable
import com.intellij.database.psi.DbColumnImpl
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* FILES files helper
*/
packageName = "com.sample;"
typeMapping = [
(~/(?i)short/) : "Short",
(~/(?i)smallint/) : "Short",
(~/(?i)bigint/) : "Long",
(~/(?i)int/) : "Integer",
(~/(?i)long/) : "Long",
(~/(?i)float|double|decimal|real/): "java.math.BigDecimal",
(~/(?i)datetime|timestamp/) : "java.time.LocalDateTime",
(~/(?i)date/) : "java.time.LocalDate",
(~/(?i)time/) : "java.time.LocalTime",
(~/(?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)}Entity"
def fields = calcFields(table)
new File(dir, className + ".java").withPrintWriter { out -> generate(table, out, className, fields) }
}
def generate(table, out, className, fields) {
out.println """package $packageName
|
|import org.seasar.doma.Entity;
|import org.seasar.doma.Table;
|import org.seasar.doma.Id;
|import org.seasar.doma.GeneratedValue;
|import org.seasar.doma.GenerationType;
|
|@Entity(immutable = true)
|@Table(name = "${table.getName()}")
|public class $className {
""".stripMargin()
// output fields
fields.each() {
if (it.annos != "") {
out.println " ${it.annos}"
}
if (it.id) {
out.println " @Id"
}
if (it.auto) {
out.println " @GeneratedValue(strategy = GenerationType.IDENTITY)"
}
out.println " public final ${it.type} ${it.name};"
out.println ""
}
out.print " public $className("
out.print fields.collect {
"${it.type} ${it.name}"
}.join(", ")
out.println ") {"
fields.each {
out.println " this.${it.name} = ${it.name};"
}
out.println " }"
out.println ""
out.println "}"
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, DbColumnImpl 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),
id : DasUtil.isPrimary(col),
auto : DasUtil.isAutoGenerated(col),
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]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment