1.使用IDEA连接数据库
略
2.选择要生成数据表实体类目标对象,点击图示选项
3.选择生成实体类目标包下
略
如果自动生成实体类对象内容不满足需求现状,在Scratches and Consoles
下Extensions/Database Tools and SQL/schema目录下找到Generate POJOs.groovy脚本文件,并修改其内容
Generate POJOs.groovy脚本内容简要介绍:
packageName = "com.xx.xx.io.dto;"
typeMapping = [
(~/(?i)int/) : "Long",
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime|timestamp/) : "LocalDateTime",
(~/(?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 { out -> generate(out, className, fields) }
}
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println "import java.time.LocalDateTime;"
out.println "import lombok.Data;"
out.println "import lombok.Data;"
out.println "import io.swagger.annotations.ApiModel;"
out.println "import io.swagger.annotations.ApiModelProperty;"
out.println ""
out.println ""
out.println "/**"
out.println "* @program: nz_backstage"
out.println "* @description: ${fields[0].tableCommoent}"
out.println "* @author: xierongbin"
out.println "* @create: "+new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())
out.println "**/"
out.println "@Data"
out.println "@ApiModel(value = \"${className}数据传输对象\",description = \"${fields[0].tableCommoent}数据传输对象\")"
out.println "public class $className {"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
out.println("/**")
out.println(" *")
out.println(" * ${it.commoent}")
out.println(" *")
out.println(" */")
out.println " @ApiModelProperty(value = \"${it.commoent}\")"
out.println " private ${it.type} ${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(),
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}[_]]/, "_")
.replace("xxx", "DTO")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
packageName
:指定实体类文件包名
typeMapping
:指定字段数据类型映射实体类数据类型
col.getName()
:获取当前字段名
col.getComment()
:获取当前字段注释
table.getComment()
:获取数据表注释