Intellij IDEA 通过数据库表逆向生成带注释的实体类文件(Generate )
生成JPA实体文件,生成的代码如下:
import ;
import .*;
import ;
import ;
import ;
@Table ( name ="image" )
@Data
@ApiModel
public class Image implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id" )
@ApiModelProperty( value="id")
private String id;
@Column(name = "entity_id" )
@ApiModelProperty( value="实体id-可关联作业单")
private String entity_id;
@Column(name = "image_name" )
@ApiModelProperty( value="图片名称")
private String image_name;
@Column(name = "image_path" )
@ApiModelProperty( value="图片路径")
private String image_path;
@Column(name = "create_time" )
@ApiModelProperty( value="创建时间")
private create_time;
@Column(name = "update_time" )
@ApiModelProperty( value="修改时间")
private update_time;
}
Generate 内容如下
import
import
import
import
import
import
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
* update by yitianRen 20200324
*/
packageName = ";"
typeMapping = [
(~/(?i)int/) : "Integer", //数据库类型和Jave类型映射关系
(~/(?i)float|double|decimal|real/): "Double",
(~/(?i)bool|boolean/) : "Boolean",
(~/(?i)datetime|timestamp/) : "",
(~/(?i)date/) : "",
(~/(?i)time/) : "",
(~/(?i)/) : "String"
]
("Choose directory", "Choose where to store generated files") { dir ->
{ it instanceof DasTable }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = javaName((), true)
def fields = calcFields(table)//更改实体生成规则
new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }//输出实体类
}
def generate(out, className, fields, table) {
"package $packageName"
""
"/**\n" +
" * \n" +
" * <p>@Date: " + ().format(("yy-MM-dd HH:mm:ss")).toString() + ".</p>\n" +
" *\n" +
" * @author linqh03\n" +
" */"
""
"import ;"
"import .*;"
"import ;"
"import ;"
"import ;"
""
"@Table ( name =\"" + () + "\" )"
"@Data"
"@ApiModel"
"public class $className implements Serializable{"
""
"private static final long serialVersionUID = 1L;"
() {
""
// 输出注释 这里和下面的 comm是一一对应的
/* if (isNotEmpty()) {//定义非空校验, != ""手写无效
"// ${}"
}*/
if ( == "id") " @Id"
if ( != "") " ${}"
" @ApiModelProperty( value=\"${}\")"
" private ${} ${};"
}
""
"}"
}
def calcFields(table) {
(table).reduce([]) { fields, col ->
def spec = (().getSpecification())
def typeStr = { p, t -> (spec).find() }.value
def comm = [
name : (),
type : typeStr,
commoent: (),
annos: "@Column(name = \"" + () + "\" )"
]
//对于表中主键自定义注解
if ("pk".equals((()))){
= "\t@Id\n"
//自增主键需要
+= "@Column(name = \"" + () + "\")"
}
fields += [comm]//字段对照
}
}
def javaName(str, capitalize) {
def s = (str)
.collect { (it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || () == 1? s : (s[0]) + s[1..-1]
}
def isNotEmpty(content) {
return content != null && ().trim().length() > 0
}