Groovy 生成entity、xml、

生成xml

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

typeMapping = [
        (~/(?i)int/)                      : "INTEGER",
        (~/(?i)float|double|decimal|real/): "DOUBLE",
        (~/(?i)datetime|timestamp/)       : "TIMESTAMP",
        (~/(?i)date/)                     : "TIMESTAMP",
        (~/(?i)time/)                     : "TIMESTAMP",
        (~/(?i)/)                         : "VARCHAR"
]

mapperPackage = "" // mapper 位置
entityPackage = "" // entity 位置
primaryKey = "" // 主键

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    // 实体类的名称
    def entityName = mapperName(table.getName(), true)
    // mapping的文件夹上一层所在的package
    mapperPackage = getPackageName(dir)
    // 实体类对应的package
    entityPackage = mapperPackage.replace(".dao", ".entity." + entityName)
    def fields = calcFields(table)
    new File(dir, entityName + "Mapper.xml").withPrintWriter { out -> generate(table, out, entityName, fields) }
}


def generate(table, out, entityName, fields) {
    out.println mappingsStart(mapperPackage + '.' + entityName + "Mapper")
    out.println sql(fields, 'all_column')
    out.println getAllWhere(fields, 'all_where')
    out.println resultMap(entityName + 'ResultMap', entityPackage, fields)
//    out.println selectById(tableName, fields, baseResultMap, base_Column_List)
//    out.println deleteById(tableName, fields)
//    out.println delete(tableName, fields, to)
//    out.println insert(tableName, fields, to)
//    out.println update(tableName, fields, to)
//    out.println selectList(tableName, fields, to, base_Column_List, baseResultMap)
    out.println mappingsEnd()

}

def getPackageName(dir) {
    return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "").replace(".mapping", "")
}
static def resultMap(baseResultMap, entityType, fields) {

    def inner = ''
    def primary = ''
    fields.each() {
        if (it.isPrimary)
            primary += '\t\t<id property="' + it.name + '" column="' + it.sqlFieldName + '"/>\n'
        else
            inner += '\t\t<result property="' + it.name + '" column="' + it.sqlFieldName + '"/>\n'
    }
    return '''\t<resultMap id="''' + baseResultMap + '''" type="''' + entityType + '''">
''' + primary + inner + '''\t</resultMap>
'''
}

def calcFields(table) {
    primaryKey = getPrimaryKey(table)
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def javaName = mapperName(col.getName(), false)
        def isPrimary = javaName.equals(primaryKey)
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           comment     : col.getComment(),
                           name        : mapperName(col.getName(), false),
                           sqlFieldName: col.getName(),
                           isPrimary   : isPrimary,
                           type        : typeStr,
                           annos       : ""]]
    }
}

def getPrimaryKey(table) {
    def key = ''
    def prKey = DasUtil.getPrimaryKey(table);
    if (prKey != null) {
        def keyRef = prKey.getColumnsRef();
        if (keyRef != null) {
            def it = keyRef.iterate();
            while (it.hasNext()) {
                // 默认只处理单主键
                key = it.next();
            }
            key = mapperName(key, false);
        }
    }
    return key
}

def mapperName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

// ------------------------------------------------------------------------ mappings
static def mappingsStart(mapper) {
    return '''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="''' + mapper + '''">
'''
}

// ------------------------------------------------------------------------ mappings
static def mappingsEnd() {
    return '''</mapper>'''
}

// ------------------------------------------------------------------------ selectById
static def selectById(tableName, fields, baseResultMap, base_Column_List) {
    return '''
    <select id="selectById" parameterType="java.lang.Integer" resultMap="''' + baseResultMap + '''">
        select
        <include refid="''' + base_Column_List + '''"/>
        from ''' + tableName + '''
        where id = #{id}
    </select>'''
}

// ------------------------------------------------------------------------ insert
static def insert(tableName, fields, parameterType) {

    return '''
    <insert id="insert" parameterType="''' + parameterType + '''">
        insert into ''' + tableName + '''
        <trim prefix="(" suffix=")" suffixOverrides=",">
            ''' + testNotNullStr(fields) + '''
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            ''' + testNotNullStrSet(fields) + '''
        </trim>
    </insert>
'''

}
// ------------------------------------------------------------------------ update
static def update(tableName, fields, parameterType) {

    return '''
    <update id="update" parameterType="''' + parameterType + '''">
        update ''' + tableName + '''
        <set>
            ''' + testNotNullStrWhere(fields) + '''
        </set>
        where id = #{id}
    </update>'''
}

// ------------------------------------------------------------------------ deleteById
static def deleteById(tableName, fields) {

    return '''
    <delete id="deleteById" parameterType="java.lang.Integer">
        delete
        from ''' + tableName + '''
        where id = #{id}
    </delete>'''
}

// ------------------------------------------------------------------------ delete
static def delete(tableName, fields, parameterType) {

    return '''
    <delete id="delete" parameterType="''' + parameterType + '''">
        delete from ''' + tableName + '''
        where 1 = 1
        ''' + testNotNullStrWhere(fields) + '''
    </delete>'''
}

// ------------------------------------------------------------------------ selectList
static def selectList(tableName, fields, parameterType, base_Column_List, baseResultMap) {

    return '''
    <select id="selectList" parameterType="''' + parameterType + '''" resultMap="''' + baseResultMap + '''">
        select
        <include refid="''' + base_Column_List + '''"/>
                from ''' + tableName + '''
        where 1 = 1
        ''' + testNotNullStrWhere(fields) + '''
        order by id desc
    </select>'''
}

// ------------------------------------------------------------------------ sql
static def sql(fields, id) {
    def str = '''\t<sql id="''' + id + '''">\n@inner@\n\t</sql> '''
    def inner = ''
    fields.each() {
        inner += ('\t\to.' + it.sqlFieldName + ',\n')
    }
    return str.replace("@inner@", inner.substring(0, inner.length() - 2))

}

static def testNotNullStrWhere(fields) {
    def inner = ''
    fields.each {
        inner += '''
        <if test="''' + it.name + ''' != null">
            and ''' + it.sqlFieldName + ''' = #{''' + it.name + '''}
        </if>\n'''
    }
    return inner
}

static def getAllWhere(fields, id) {
    def str = '''\t<sql id="''' + id + '''">@inner@\n\t</sql> '''
    def inner = ''
    fields.each {
        inner += '''
        <if test="''' + it.name + ' != null and '  + it.name + ''' != ''">
            and o.''' + it.sqlFieldName + ''' = #{''' + it.name + '''}
        </if>'''
    }
    return str.replace("@inner@", inner)

}

static def testNotNullStrSet(fields) {
    def inner = ''
    fields.each {
        inner += '''
        <if test="''' + it.name + ''' != null">
            #{''' + it.name + '''},
        </if>\n'''
    }

    return inner
}

static def testNotNullStr(fields) {
    def inner1 = ''
    fields.each {
        inner1 += '''
        <if test = "''' + it.name + ''' != null" >
        \t''' + it.sqlFieldName + ''',
        </if>\n'''
    }

    return inner1
}

生成实体类

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.SimpleDateFormat

packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint/)      : "Integer",
        (~/(?i)int/)                             : "Long",
        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp|date|time/)    : "Date",
        (~/(?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 }.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, className, fields, table) }

}

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

def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import io.swagger.annotations.ApiModelProperty;"
    out.println "import com.bj58.qiaoyu.common.persistence.DataEntity;"
    out.println "import com.bj58.qiaoyu.util.DateUtil;"
    out.println "import com.alibaba.fastjson.JSONException;"
    out.println "import com.alibaba.fastjson.JSONObject;"
    out.println "import lombok.Data;"
    out.println "import lombok.experimental.Accessors;"
    out.println "import javax.persistence.Table;"
    out.println "import javax.persistence.Column;"
    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 IDEA\n" + //1. 修改idea为自己名字
            " * @Date " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
            " */"

    out.println ""
    out.println "@Data"
    out.println "@Accessors(chain = true)"
    out.println "@Table ( name =\"" + table.getName() + "\")" //2. schema = \"后面添加自己的表空间名称(mysql可以不添加, 不用这个schema属性也行)
    out.println "public class $className  extends DataEntity<$className> {"
    out.println ""

    fields.each() {
        out.println ""
        //输出注释和属性注解
        out.println "\t/**"
        out.println "\t * ${it.commoent.toString()}"
        out.println "\t */"
        out.println "\t@ApiModelProperty(\"${it.commoent.toString()}\")"
        // 输出行注解
        out.println "\t@Column(name = \"${it.colName}\")"
        // 输出行属性
        out.println "\tprivate ${it.type} ${it.name};"
    }

    out.println ""
    out.println "\t@Override"
    out.println "\tpublic JSONObject toJsonObject() throws JSONException {"
    out.println "\t\tJSONObject json = new JSONObject();"
    fields.each() {
        if (it.type == "Date") {
            out.println "\t\tjson.put(\"${it.name}\", null == ${it.name} ? \"\" : DateUtil.getDateToString(${it.name}));"
        } else {
            out.println "\t\tjson.put(\"${it.name}\", null == ${it.name} ? \"\" : ${it.name});"
        }
    }
    out.println "\t\treturn json;"
    out.println "\t}"
    out.println ""

    out.println ""
    out.println "\t@Override"
    out.println "\tpublic Map<String, Object> toMap() {"
    out.println "\t\tMap<String, Object> res = new HashMap<>();"
    fields.each() {
        if (it.type == "Date") {
            out.println "\t\tres.put(\"${it.name}\", null == ${it.name} ? \"\" : DateUtil.getDateToString(${it.name}));"
        } else {
            out.println "\t\tres.put(\"${it.name}\", null == ${it.name} ? \"\" : ${it.name});"
        }
    }
    out.println "\t\treturn res;"
    out.println "\t}"
    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
        def comm = [
                colName : col.getName(),
                name    : javaName(col.getName(), false),
                type    : typeStr,
                commoent: col.getComment(),
//                annos   : "\t@Column(name = \"" + col.getName() + "\" )"
        ]
//        if ("id".equals(Case.LOWER.apply(col.getName())))
//            comm.annos += ["@Id"]
        fields += [comm]
    }
}


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

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

static String changeStyle(String str, boolean toCamel) {
    if (!str || str.size() <= 1)
        return str

    if (toCamel) {
        String r = str.toLowerCase().split('_').collect { cc -> Case.LOWER.apply(cc).capitalize() }.join('')
        return r[0].toLowerCase() + r[1..-1]
    } else {
        str = str[0].toLowerCase() + str[1..-1]
        return str.collect { cc -> ((char) cc).isUpperCase() ? '_' + cc.toLowerCase() : cc }.join('')
    }
}

posted @ 2022-01-05 17:59  GHzz  阅读(164)  评论(0编辑  收藏  举报