IDEA -- 自动创建POJO

2019-05-18  本文已影响0人  一波怼

1. maven依赖

springboot2、spring-data-jpa、lombok

使用spring-data-jpa的时候,我们往往不需要生成mapper相关的文件,只需要自动生成POJO类,提高开发效率,这里总结了下自己使用IDEA实现自动生成POJO的方式

2. 步骤

2.1. 在IDEA中连接数据库

idea-01.png idea-02.png

2.2. 选择数据库表

idea-03.png

2.3. 修改groovy配置文件

idea-04.png

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

  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.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 org.hibernate.annotations.DynamicInsert;"
    out.println "import org.hibernate.annotations.DynamicUpdate;"
    out.println ""
    out.println "import javax.persistence.*;"
    out.println ""
    out.println "/**"
    out.println " * @author wcy-auto"
    out.println " **/"
    out.println "@NoArgsConstructor"
    out.println "@AllArgsConstructor"
    out.println "@Getter"
    out.println "@Builder"
    out.println "@ToString"
    out.println "@DynamicUpdate"
    out.println "@DynamicInsert"
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "public class $className extends BaseEntity {"
    out.println ""

    // id、createDate、updateDate这些字段我使用了一个BaseEntity,所有的pojo继承此基类,所以不需要创建数据库中的这三个字段,需要的可以自行调整
    /*if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
        out.println "    @Id"
        out.println "    @GeneratedValue(strategy=GenerationType.IDENTITY)"
    }*/
    fields.each() {
        // 这一层if根据需要看是否要保留
        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

idea-05.png

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

package fastcloud.management.pojo;

import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;

/**
 * @author wcy-auto
 **/
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
@ToString
@DynamicUpdate
@DynamicInsert
@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;

}
上一篇下一篇

猜你喜欢

热点阅读