欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

idea 逆向生成jpa 实体类

程序员文章站 2022-06-15 10:55:15
...

本文参考操作流程,记录下亲测可用的groovy 脚本,供以后查用及大家分享学习.

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

import java.io.*
import java.text.SimpleDateFormat
import java.util.Date

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

//自动根据选择文件夹获取
packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Long",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)bool|boolean/)                    : "Boolean",
        (~/(?i)datetime|timestamp/)              : "Date",
        (~/(?i)date/)                            : "java.sql.Date",
        (~/(?i)time/)                            : "java.sql.Time",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?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)
    packageName = getPackageName(dir)
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
    printWriter.withPrintWriter { out -> generate(out, table, className, fields) }
    //中文注释会乱码
    // new File(dir, className + ".java").withPrintWriter { out -> generate(out, table, className, fields) }
}


// 获取包所在文件夹路径
def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}


def generate(out, table, className, fields) {
    def tableName = table.getName()
    out.println "package $packageName"
    out.println ""
    out.println "import lombok.Data;"
    out.println ""
    out.println "import javax.persistence.*;"
    out.println "import java.io.Serializable;"
    out.println "import java.util.Date;"
    out.println ""

    Set types = new HashSet()

    fields.each() {
        types.add(it.type)
    }

    if (types.contains("Date")) {
        out.println "import java.util.Date;"
    }

    if (types.contains("InputStream")) {
        out.println "import java.io.InputStream;"
    }

    /*添加注释*/
    out.println ""
    out.println "/**\n" +
            " * @Description  \n" +
            " * @Author  MichaelZ\n" +
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"
    out.println ""


    out.println "@Data"
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "public class $className  implements Serializable {"
    out.println ""
    out.println genSerialID()

    // 判断自增
    if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
        out.println "\[email protected]"
        out.println "\[email protected](strategy=GenerationType.IDENTITY)"
    }
    fields.each() {
        // 输出注释
        if (isNotEmpty(it.comment)) {
            out.println "\t/**"
            out.println "\t * ${it.comment.toString()}"
            out.println "\t */"
            out.println "\[email protected](value = \"$it.comment\")"
        }

        if (it.annos != "") out.println "  ${it.annos}"
        out.println "\[email protected](name = \"${it.colum}\",columnDefinition =  \"${it.columnDefinition}\") "
        out.println "\tprivate ${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           : "",
                           columnDefinition: col.getDataType()
                   ]]
    }
}

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


def isNotEmpty(content) {
    return content != null && content.toString().trim().length() > 0
}

static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  " + Math.abs(new Random().nextLong()) + "L;"
}


生成的java 实体类如下:

package com.xxx.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @Description  
 * @Author  MichaelZ
 * @Date 2019-10-14 
 */

@Data
@Entity
@Table(name = "test_table")
public class TestTableimplements Serializable {

	private static final long serialVersionUID =  1399483426396845015L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "id",columnDefinition =  "int(11)") 
	private Long id;

	/**
	 * 小区id
	 */
	@ApiModelProperty(value = "小区id")
	@Column(name = "area_id",columnDefinition =  "int(11)") 
	private Long areaId;
	...
}