生成SpringJPA的实体可以使用编译器中自带的配置:
Project Structure>> Facets ,选择JPA即可
image.png
然后打开Persistence,右键选择,见下图:
image.png
但是得到的实体类不太令人满意,所以这里我们可以选择利用groovy脚本生成实体类,选择Scratches>>Generate POJOs.groovy:
image.png
脚本可参考下面代码:
import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.demo;" //这里要换成自己项目 实体的包路径
typeMapping = [
(~/(?i)int/) : "Integer", //数据库类型和Jave类型映射关系
(~/(?i)float|double|decimal|real/): "Double",
(~/(?i)bool|boolean/) : "Boolean",
(~/(?i)datetime|timestamp/) : "java.util.Date",
(~/(?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 && it.getKind() == ObjectKind.TABLE }.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, table, className, fields) }
}
def generate(out, table, className, fields) {
def tableName = table.getName()
out.println "package $packageName"
out.println ""
out.println "import lombok.Data;"
out.println ""
out.println "import javax.persistence.*;"
out.println "import java.io.Serializable;"
out.println ""
out.println "@Data"
out.println "@Entity"
out.println "@Table(name = \"$tableName\")"
out.println "public class $className implements Serializable {"
out.println ""
if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
out.println "\t@Id"
out.println "\t@GeneratedValue(strategy=GenerationType.IDENTITY)"
}
fields.each() {
if (it.annos != "") out.println " ${it.annos}"
out.println "\t@Column(name = \"${it.colum}\")"
if (it.colum != it.name) {
out.println "\tprivate ${it.type} ${it.colum};"
}else {
out.println "\tprivate ${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),
colum: col.getName(),
type : typeStr,
annos: ""]]
}
}
def javaName(str, capitalize) {
def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
.join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
这里提一句,我也是参考了网上其他人的例子,但是发现生成的实体有问题,没有@Column注解,而且字段名与数据库也不匹配,所以修改了一下。(不知道是我编辑器的问题还是什么原因,不过以上规则确实是我期望得到的)
然后从Database选择要生成的表实体:
image.png
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Data
@Entity
@Table(name = "t_test")
public class TTest implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "code")
private String code;
@Column(name = "name")
private String name;
@Column(name = "time")
private java.util.Date time;
@Column(name = "lastUpdateTime")
private java.util.Date lastUpdateTime;
}
对了,还要在pom文件中加入lombok的依赖;
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
7D28525A-F2E4-49BD-887A-A0129DBAAE88_meitu_1.jpg
网友评论