美文网首页
自定义JPA实体生成工具,整合Swagger注释

自定义JPA实体生成工具,整合Swagger注释

作者: JO鸡尾酒 | 来源:发表于2019-07-15 11:39 被阅读0次

intellij idea,生成java实体

实体特点

1、lombok 模式

2、单一主键自增支持

3、非空采用普通类型,可空采用包装类型

4、非null默认值默认复制

5、数据库注释同步,采用swagger模式添加

生成效果如下:

@Data

@Entity

@Table(name = "key_value")

@ApiModel(description = "单一少量数据结构化记录")

public class KeyValueEntity {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "id")

    private int id;

    @Basic

    @Column(name = "key_name")

    @ApiModelProperty("键值")

    private String keyName;

    @Basic

    @Column(name = "version")

    @ApiModelProperty("版本,时间到秒记录")

    private int version;

    @Basic

    @Column(name = "content")

    @ApiModelProperty("数据信息")

    private String content;

    @Basic

    @Column(name = "state")

    @ApiModelProperty("状态,0为发布,1为编辑")

    private byte state = 1;

    @Basic

    @Column(name = "create_at")

    private Timestamp createAt;

    @Basic

    @Column(name = "update_at")

    private Timestamp updateAt;

}

相关脚本

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

*/

packageName =""

typeMapping = [

(~/(?i)tinyint/)              :"Byte",

(~/(?i)smallint/)            :"Short",

(~/(?i)bigint/)              :"Long",

(~/(?i)mediumint|int|integer/):"Integer",

(~/(?i)float/)                :"Float",

(~/(?i)double|decimal|real/)  :"Double",

(~/(?i)decimal/)              :"BigDecimal",

(~/(?i)timestamp/)            :"Timestamp",

(~/(?i)datetime|date/)        :"Date",

(~/(?i)time/)                :"Time",

(~/(?i)/)                    :"String"

]

typeMapping2 = [

(~/(?i)tinyint/)              :"byte",

(~/(?i)smallint/)            :"short",

(~/(?i)bigint/)              :"long",

(~/(?i)mediumint|int|integer/):"int",

(~/(?i)float/)                :"float",

(~/(?i)double|decimal|real/)  :"double",

(~/(?i)decimal/)              :"BigDecimal",

(~/(?i)timestamp/)            :"Timestamp",

(~/(?i)datetime|date/)        :"Date",

(~/(?i)time/)                :"Time",

(~/(?i)/)                    :"String"

]

typeCanDefault = [

(~/(?i)tinyint/)              :true,

(~/(?i)smallint/)            :true,

(~/(?i)bigint/)              :true,

(~/(?i)mediumint|int|integer/):true,

(~/(?i)float/)                :true,

(~/(?i)double|decimal|real/)  :true,

(~/(?i)decimal/)              :false,

(~/(?i)timestamp/)            :false,

(~/(?i)datetime|date/)        :false,

(~/(?i)time/)                :false,

(~/(?i)/)                    :true

]

FILES.chooseDirectoryAndSave("Choose directory","Choose where to store generated files") { dir ->

SELECTION.filter { itinstanceof DasTable }.each { generate(it, dir) }

}

// 获取包所在文件夹路径

def getPackageName(dir) {

return dir.toString().replaceAll("\\\\",".").replaceAll("/",".").replaceAll("^.*src(\\.main\\.java\\.)?","") +";"

}

def generate(table, dir) {

def className = javaName(table.getName(),true)

def fields = calcFields(table)

packageName = getPackageName(dir)

new File(dir, className +"Entity.java").withPrintWriter { out -> generate(out, className, table.getComment(), fields, table) }

}

def generate(out, className, comment, fields, table) {

out.println"package $packageName"

    out.println""

    out.println"import io.swagger.annotations.ApiModelProperty;"

    out.println"import io.swagger.annotations.ApiModel;"

    out.println""

    out.println"import lombok.Data;"

    out.println""

    out.println"import javax.persistence.*;"

    Set types =new HashSet()

fields.each() {

types.add(it.type)

}

if (types.contains("BigDecimal")) {

out.println"java.math.BigDecimal"

    }

if (types.contains("Timestamp")) {

out.println"import java.sql.Timestamp;"

    }

if (types.contains("Date")) {

out.println"import java.util.Date;"

    }

if (types.contains("Time")) {

out.println"import java.util.Time;"

    }

out.println""

    out.println"/**\n" +

(comment ==null ?"" : (" * ${comment}\n * \n")) +

" * @author yaojunguang\n" +

" * create time: " +new Date().toString() +".\n" +

" */"

    out.println""

    out.println"@Data"

    out.println"@Entity"

    out.println"@Table(name = \"${table.getName()}\")"

    out.println"@ApiModel(description = \"<a href='/web/swift/${className}Entity' target=_blank>" + (comment ==null ?"${className}Entity" :"${comment}") +"</a>\")"

    out.println"public class ${className}Entity {"

    fields.each() {

out.println""

        // 输出注释

        if (it.annos !="") out.println"    ${it.annos}"

        if (isNotEmpty(it.comm)) {

out.println"    @ApiModelProperty(\"${it.comm}\")"

        }

out.print"    private ${it.type} ${it.name}"

        if (it.default !=null) {

out.println" = ${it.default};"

        }else {

out.println";"

        }

}

out.println""

//    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

if (col.isNotNull()) {

typeStr = typeMapping2.find { p, t -> p.matcher(spec).find() }.value

}

def anno ="@Basic\n    @Column(name = \"" + columnName(col.getName()) +"\")"

        if ("id".equals(Case.LOWER.apply(col.getName())) && DasUtil.isPrimary(col)) {

anno ="@Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    @Column(name = \"" + col.getName() +"\")"

            typeStr ="int"

        }

fields += [[

name  : javaName(col.getName(),false),

type  : typeStr,

comm  : col.getComment(),

default: typeCanDefault.find { p, t -> p.matcher(spec).find() }.value ? col.getDefault() :null,

annos  : anno]]

}

}

def columnName(name) {

if ("desc".equals(name)) {

return "`desc`"

    }

if ("limit".equals(name)) {

return "`limit`"

    }

if ("left".equals(name)) {

return "`left`"

    }

if ("right".equals(name)) {

return "`right`"

    }

if ("like".equals(name)) {

return "`like`"

    }

if ("usage".equals(name)) {

return "`usage`"

    }

return name

}

def isNotEmpty(content) {

return content !=null && content.toString().trim().length() >0

}

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]

}

相关文章

网友评论

      本文标题:自定义JPA实体生成工具,整合Swagger注释

      本文链接:https://www.haomeiwen.com/subject/hoicwqtx.html