import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
import java.text.SimpleDateFormat
import java.lang.*;
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
packageName = ""
// 将数据库表类型转换为Java对应的属性
typeMapping = [
(~/(?i)bigint/) : "Long",
(~/(?i)int|tinyint|smallint|mediumint/) : "Integer",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?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) {
// 去除表前缀 “tb_user" -> User.java
tablename=table.getName();
if(tablename.indexOf("_")!=-1){
tablename=tablename.substring(tablename.indexOf("_"));
}
// 生成的java类名
def className = javaName(tablename, true)
// 具体的表字段属性,table只有表明的属性,getName()方法可调用
def fields = calcFields(table)
// 生成你选中的路径,产生相对位置的包名
packageName = getPackageName(dir)
// 创建一个".java"的后缀文件,格式为UTF-8,中文格式
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
// 写入到文件,里面进行具体的内容编写
printWriter.withPrintWriter { out -> generate(out, className, fields, table.getName(), 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, classNameAll, table) {
// 生成的包名
out.println "package $packageName"
// 换行
out.println ""
// 准备一个set存放type
Set types = new HashSet()
// 表字段遍历
fields.each() {
// 将表字段类型加入到types里面
types.add(it.type)
}
// 当识别的字段类型和DATE相同,那么就输出导入LocalDateTime
if (types.contains("Date")) {
out.println "import java.time.LocalDateTime;"
}
//out.println "import import java.util.Date;"
// 同上
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("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println "import java.io.Serializable;"
out.println "import javax.persistence.*;"
out.println ""
// 输出创建文件信息 @Description无法读取到,需要手动编写
out.println "/**\n" +
" * @Description Todo\n" +
" * @Author hikktn\n" +
" * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
" */"
// 该对象为entity
out.println "@Entity"
// 声明对应的表映射关系
out.println "@Table(name = \"$classNameAll\")"
// 输出主体的表明创建
out.println "public class $className implements Serializable {"
out.println ""
// UUID的随机创建
out.println genSerialID()
// 字段遍历,这里进行表字段的单独处理,主要创建各种字段的类型转换,主键确认,时间类型转换
fields.each() {
out.println ""
// 输出注释
println it.commoent
if (isNotEmpty(it.commoent)) {
out.println "\t/**"
out.println "\t * ${it.commoent.toString()}"
out.println "\t */"
}
if (it.colName == "id") {
out.println "\t@Id"
out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
}
out.println "\t@Column(name ="+"\"${it.colName.toupperCase()}\""+")"
// if (it.annos != "") out.println " ${it.annos.replace("[@Id]", "")}"
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};"
}
// 输出get/set方法
fields.each() {
out.println ""
out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
out.println "\t\treturn this.${it.name};"
out.println "\t}"
out.println ""
out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
out.println "\t\tthis.${it.name} = ${it.name};"
out.println "\t}"
}
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), // 表字段名(无下划线)
type : typestr, // 表类型
commoent: col.getComment(), // 表字段说明
annos : ""] // 主键标识 [@Id]
/* if(isNotEmpty(col.getComment())){
comm.annos +="\r\n\t@ApiField(desc = \""+col.getComment()+"\")"
}*/
fields += [comm]
}
}
def javaName(str, capitalize) {
// def s = str.split(/(?<=[^\p{IsLetter}])/).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
}
static String changeStyle(String str, boolean toCamel) {
if (!str || str.size() <= 1)
return str
if (toCamel) {
String r = str.toLowerCase().split('_').collect { cc -> Case.LOWER.apply(cc).capitalize() }.join('')
return r[0].toLowerCase() + r[1..-1]
} else {
str = str[0].toLowerCase() + str[1..-1]
return str.collect { cc -> ((char) cc).isUpperCase() ? '_' + cc.toLowerCase() : cc }.join('')
}
}
static String genSerialID() {
return "\tprivate static final long serialVersionUID = " + Math.abs(new Random().nextLong()) + "L;"
}
具体效果:
package com.hikktn.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
/**
* @Description 权限表
* @Author hikktn
* @Date 2021-07-09
*/
@Entity
@Table(name = "sec_permission")
public class SecPermission implements Serializable {
private static final long serialVersionUID = 68310868056789046L;
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name ="ID")
private Long id;
/**
* 权限名
*/
@Column(name ="NAME")
private String name;
/**
* 类型为页面时,代表前端路由地址,类型为按钮时,代表后端接口地址
*/
@Column(name ="URL")
private String url;
/**
* 权限类型,页面-1,按钮-2
*/
@Column(name ="TYPE")
private Integer type;
/**
* 权限表达式
*/
@Column(name ="PERMISSION")
private String permission;
/**
* 后端接口访问方式
*/
@Column(name ="METHOD")
private String method;
/**
* 排序
*/
@Column(name ="SORT")
private Integer sort;
/**
* 父级id
*/
@Column(name ="PARENT_ID")
private Long parentId;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getType() {
return this.type;
}
public void setType(Integer type) {
this.type = type;
}
public String getPermission() {
return this.permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getmethod() {
return this.method;
}
public void setMethod(String method) {
this.method = method;
}
public Integer getSort() {
return this.sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Long getParentId() {
return this.parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。