SpringBoot JPA 自动生成代码 (一) 生成实体类,下面脚本如何使用可以参考这篇博客;
这里记录下使用 Mybatis-Plus 时生成实体类:
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.text.SimpleDateFormat
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = "com.sample;"
typeMapping = [
(~/(?i)int/) : "Integer",
(~/(?i)float|double|decimal|real/): "double",
(~/(?i)datetime|timestamp/) : "LocalDateTime",
(~/(?i)date/) : "LocalDate",
(~/(?i)time/) : "LocalDateTime",
(~/(?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 className = javaClassName(table.getName(), true)
def fields = calcFields(table)
packageName = getPackageName(dir)
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter { out -> generate(out, className, fields, table) }
// new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }
}
// 获取包所在文件夹路径
def getPackageName(dir) {
return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
def generate(out, className, fields, table) {
out.println "package $packageName"
out.println ""
out.println "import java.io.Serializable;"
out.println "import lombok.Data;"
Set types = new HashSet()
out.println "import com.baomidou.mybatisplus.annotation.TableName;"
// 表字段遍历
fields.each() {
// 将表字段类型加入到types里面
types.add(it.type)
}
if (types.contains("InputStream")) {
out.println "import java.io.InputStream;"
}
if (types.contains("LocalDateTime")) {
out.println "import java.time.LocalDateTime;"
out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
out.println "import org.springframework.format.annotation.DateTimeFormat;"
}
if (types.contains("LocalDate")) {
out.println "import java.time.LocalDate;"
}
if (types.contains("BigDecimal")) {
out.println "import java.math.BigDecimal;"
}
if (types.contains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
out.println ""
out.println "/**\n" +
" * @Description \n" +
" * @author linmengmeng\n" + //1. 修改idea为自己名字
" * @since " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
" */"
out.println "@Data"
out.println "@TableName(\"" + table.getName() + "\")"
out.println "public class $className implements Serializable {"
out.println ""
out.println genSerialID()
out.println ""
fields.each() {
out.println ""
// 输出注释
println it.commoent
// 输出注释 it 对象: [name:tenantId, type:String, annos:]
if (isNotEmpty(it.commoent)) {
out.println "\t/**"
out.println "\t * ${it.commoent.toString()}"
out.println "\t */"
}
// Spring Data JPA
/*if (it.colName == "id") {
out.println "\t@Id"
out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
}*/
// Mybatis-plus
if (it.colName == "id") {
out.println "\t@TableId(value = \"id\", type = IdType.ASSIGN_UUID)"
}
if (it.annos != "") out.println " ${it.annos}"
// if ((it.annos+"").indexOf("[@Id]") >= 0) out.println "\t@TableId(value = \"id\", type = IdType.ASSIGN_UUID)"
String type = it.type;
if (type == "LocalDateTime") {
out.println "\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", locale = \"zh\", timezone = \"GMT+8\")";
out.println "\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")";
}
out.println "\tprivate ${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
if ("Date".equals(typeStr)) {
typeStr = "LocalDateTime"
}
def comm = [
colName : col.getName(), // 表字段名
name : javaName(col.getName(), false), // 表字段名(无下划线)
//name : javaClassName(col.getName(), false),
type : typeStr, // 表类型
commoent: col.getComment(), // 表字段说明
annos: ""] // 主键标识 [@Id]
fields += [comm]
}
}
// 这里是处理数据库表前缀的方法,这里处理的是t_xxx命名的表
// 已经修改为使用javaName, 如果有需要可以在def className = javaName(table.getName(), true)中修改为javaClassName
// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
// 如果你不需要去掉表的前缀,那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
def javaClassName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
// 去除开头的 airadar_
s = s[7..s.size() - 1]
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
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]
// 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]
}
def isNotEmpty(content) {
return content != null && content.toString().trim().length() > 0
}
//生成序列化的serialVersionUID
static String genSerialID() {
return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"
}
生成的实体类效果如下:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @Description XX信息历史表
* @author linmengmeng
* @since 2022-09-27 16:08:06
*/
@Data
@TableName("airadar_asset_vul_info_his")
public class AssetVulInfoHis implements Serializable {
private static final long serialVersionUID = 7686024001170977261L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
/**
* 源主键
*/
private String assVulId;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
/**
* 入库时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime insertTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime closingDate;
/**
* 修改人名称
*/
private String updateName;
}