目录
前言
为了提高开发效率,对于简单但纯粹费时的dao,domain,service我们都希望能根据数据库字段自动生成,于是idea提供了能执行自定义groovy脚本的方式来生成需要的实体类等。
Intellij Idea自动生成jpa实体类
1.idea连接数据库
如果还未安装驱动,左下角会提示安装,先点击安装即可。
2.添加自定义groovy脚本
(1)对任意表 右键 > Scripted Extensions > Go To Scripts Diretory 就会跳转到脚本所在目录
(2)通过上一步跳转的目录,可以看到目录已经有一个自带的脚本 Generate POJOs.groovy。后续我们自定义的脚本就放在这里,执行的时候会读取该目录下的所有可执行脚本,这样便可以选择需要执行的脚本。
(3)先展示下添加脚本后效果如下图所示:
2.1.domain脚本
复制添加以下脚本,并放到脚本目录下(有兴趣可以自己写groovy脚本放置进去就可以生成自己想要的格式,groovy还是挺易入门的)对应的脚本生成的效果附在脚本后
2.1.1 脚本
Generate DOMAINs.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
//这里记得改成你的包路径
packageName = "com.alone.jpa.domain;"
typeMapping = [
(~/(?i)tinyint|smallint|mediumint/) : "Integer",
(~/(?i)int/) : "Long",
(~/(?i)float|double|decimal|real/) : "double",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)datetime|timestamp|date|time/) : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?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)
PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "utf-8"))
output.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 "import javax.persistence.*;"
out.println "import java.io.Serializable;"
out.println ""
out.println "@Entity"
out.println "@Table(name = \"$tableName\")"
out.println "public class $className implements Serializable{"
out.println ""
out.println generateSerialId()
out.println ""
fields.each() {
if (isNotEmpty(it.commoent)) {
out.println "\t/**"
out.println "\t * ${it.commoent.toString()}"
out.println "\t */"
}
if (it.annos != "") out.println " ${it.annos}"
//判断如果是主键id则多打印注解@Id,@GeneratedValue(当然前提是你的表主键id字段名是id或_id,不是的话这里自己改成你的主键字段)
if (it.colum.equalsIgnoreCase("id") || it.colum.equalsIgnoreCase("_id")){
out.println "\t@Id"
out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
}
out.println "\t@Column(name = \"${it.colum}\")"
out.println "\tprivate ${it.type} ${it.name};"
out.println ""
}
//生成get set
fields.each() {
out.println ""
out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
out.println " return ${it.name};"
out.println " }"
out.println ""
out.println "\tpublic 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(),
commoent: col.getComment(),
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}[_]]/, "_")
//如果你的表有前缀类似 t_ 需要去掉那这里的注释要启用,同样的前缀多长就 size()-长度
//s = s[1..s.size() - 1]
capitalize || s.length() == 1<