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;
}

複製代碼
相關文章
相關標籤/搜索