本篇博客主要介绍如何使用IDEA连接数据库,并且自动生成与table对应的实体类,省时省力。
项目环境:SpringBoot + Spring JPA + Lombok + DB2
1.连接DB2数据库,打开IDEA,找到最右侧的Database,创建一个新的DB2的连接:
2.注意这里要选Type4和IBM Db2:
3.db信息填完之后再点击Schemas,选择你需要连接的数据库:
4.这个时候你就能在IDEA中看到数据库的详细信息了,如果加载慢,尝试多手动点击刷新按钮即可:
5.选中任意table点击鼠标右键,Scripted Extensions --> GoTo Scripts Directory,找到Generate POJOs.groovy文件,这个是IDEA生成Entity的初始脚本模板:
6.往往IDEA生成的初始模板不能满足我们的需求,所以我们可以复制Generate POJOs.groovy并重命名为Generate POJOs-new.groovy,下面是我自己写的groovy脚本:
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable
* PROJECT project
* FILES files helper
*/
//1.这里更改成你想要的包名
packageName = "package com.example.demo;"
//2.这里是DB2的类型typeMapping,自行变换成自己需要的
typeMapping = [
(~/(?i)int/) : "Integer",
(~/(?i)float|double|decimal|real/): "BigDecimal",
(~/(?i)datetime|timestamp/) : "LocalDateTime",
(~/(?i)date/) : "LocalDate",
(~/(?i)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)
def fields = calcFields(table)
new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }
}
def generate(out, className, fields, table) {
//3.增加你需要导入的包或者添加的注解
out.println "package $packageName"
out.println ""
out.println "import lombok.AllArgsConstructor;"
out.println "import lombok.Data;"
out.println "import lombok.NoArgsConstructor;"
out.println "import lombok.experimental.SuperBuilder;"
out.println "import javax.persistence.*;"
out.println "import java.io.Serializable;"
out.println "import java.math.BigDecimal;"
out.println "import java.time.LocalDate;"
out.println "import java.time.LocalDateTime;"
out.println ""
out.println "@Data"
out.println "@SuperBuilder"
out.println "@NoArgsConstructor"
out.println "@AllArgsConstructor"
out.println "@Entity"
out.println "@Table(name = \"${table.getName()}\", schema = \"FOS\")"
out.println "public class $className implements Serializable{"
out.println ""
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
//4.增加@Column注解
out.println " @Column(name= = \"${it.filed}\")"
out.println " private ${it.type} ${it.name};"
out.println ""
}
out.println ""
//5.因为使用Lombok插件,注释Getter和Setter方法
// 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,
//6.增加filed属性,给@Column获取table中的属性名
filed: col.getName(),
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]
}
注意,生成的Entity不能自动识别到table中的主键,所以需要手动修改并添加@Id注解