IDEA -- 自动生成POJO

1. maven依赖

springboot二、spring-data-jpa、lombok

使用 spring-data-jpa的时候,咱们每每不须要生成mapper相关的文件,只须要自动生成POJO类,提升开发效率,这里总结了下本身使用IDEA实现自动生成POJO的方式

2. 步骤

2.1. 在IDEA中链接数据库



2.2. 选择数据库表


2.3. 修改groovy配置文件


参照上面的步骤对配置文件进行个性化修改:

1. 注意修改包名称packageName
2. 添加须要的注解

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.text.DateFormat
import java.text.SimpleDateFormat

/* * Available context bindings: * SELECTION Iterable<DasObject> * PROJECT project * FILES files helper */
packageName = "fastcloud.management.beans.pojo;"  //这里要换成本身项目 实体的包路径
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("utf-8") { 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.*;"
    out.println "import fastcloud.management.base.BaseEntity;" // 这里自定义须要引入的包
    out.println "import lombok.experimental.Accessors;"
    out.println ""
    out.println "import javax.persistence.*;"
    out.println ""
    out.println "/**"
    out.println " * @author wcy-auto"
    out.println " **/"
    out.println "@Data"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    out.println "@Accessors(chain = true)"
    out.println "@ToString(callSuper = true)"
    out.println "@EqualsAndHashCode(callSuper = true)"
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "public class $className extends BaseEntity {"
    out.println ""
    // 这里若是须要生成id字段须要打开
    /*if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) { out.println " @Id" out.println " @GeneratedValue(strategy=GenerationType.IDENTITY)" }*/
    fields.each() {
        if (it.name != "id" && it.name != "createTime" && it.name != "updateTime") {
            if (it.comment != "" && it.comment != null) {
                out.println " /**"
                out.println " * ${it.comment}"
                out.println " **/"
            }
            if (it.annos != "") out.println " ${it.annos}"
            if (it.colum != it.name) {
                out.println " @Column(name = \"${it.colum}\")"
            }

            out.println " private ${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,
 comment: col.getComment(),
                           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]
}复制代码

2.4. 生成POJO


以后选择要生成的目标文件夹,生成后的POJO以下:


package com.zyzh.zz.trade.config;

import lombok.*;
import javax.persistence.*;

/*** @author wcy-auto**/
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
@ToString
@Entity
@Table(name = "dept")
public class Dept extends BaseEntity {
    /*** 上级部门ID**/
    @Column(name = "parent_id")
    private Integer parentId;
    /*** 部门名称**/
    private String name;
    /*** 1 - 正常,0 - 删除**/
    @Column(name = "del_flag")
    private Integer delFlag;
}

复制代码
相关文章
相关标签/搜索