自定义生成service dao entity xml

自定义生成service dao entity xml

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"
]
mapperPackage = "" // mapper 位置
entityPackage = "" // entity 位置
servicePackage = "" // service 位置
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 className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)

    
    def entitvDir = dir.toString()
    def entityFileName = className + '.java'
    entityPackage = packageName + ".entity"

    def mapperDir = entitvDir + '/../dao'
    def mapperFileName = className + 'Mapper.java'
    mapperPackage = packageName + ".dao"

    def serviceDir = entitvDir + '/../service'
    def serviceFileName = className + 'Service.java'
    servicePackage = packageName + ".service"

    def xmlDir = mapperDir + "/mapping"
    def xmlFileName = className + 'Mapper.xml'


    // entity
    new File(entitvDir, entityFileName).withPrintWriter { out -> generateEntity(out, className, fields, table) }
    // xml
    new File(xmlDir, xmlFileName).withPrintWriter { out -> generateXml(out, className, fields, table) }
    // mapper
    new File(mapperDir, mapperFileName).withPrintWriter { out -> generateMapper(out, className) }
    // service
    new File(serviceDir, serviceFileName).withPrintWriter { out -> generateService(out, className) }

}



// 生成实体类
def generateEntity(out, className, fields, table) {
    out.println "package $entityPackage;"
    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 GHz\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.sqlFieldName}\")"
        // 输出行属性
        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 "}"
}

// 生成 xml
def generateXml(out, className, fields, table) {
    out.println mappingsStart(mapperPackage + '.' + className + "Mapper")
    out.println sql(fields, 'all_column')
    out.println getAllWhere(fields, 'all_where')
    out.println resultMap(className + 'ResultMap', entityPackage + "." + className, fields)
    out.println mappingsEnd()
}

def generateMapper(out, className) {
    def str = '''package @package@;

import com.bj58.qiaoyu.common.persistence.BaseDao;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import @entityPackage@;

/**
 * @Description
 * @Author GHz
 * @Date @Date@
 */

@Mapper
@Repository
public interface @mapperName@ extends BaseDao<@entityName@> {

}
'''
    out.println str.replace("@package@", mapperPackage)
            .replace("@entityPackage@", entityPackage + "." + className)
            .replace("@mapperName@", className + "Mapper")
            .replace("@entityName@", className)
            .replace('@Date@', new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
}

def generateService(out, className) {
    def str = '''package @package@;

import com.bj58.qiaoyu.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import @mapperPackage@;
import @entityPackage@;

/**
 * @Description
 * @Author GHz
 * @Date @Date@
 */
@Service
public class @serviceName@ extends BaseService<@mapperName@, @entityName@> {

}
'''
    out.println str.replace('@package@', servicePackage)
            .replace('@mapperPackage@', mapperPackage + "." + className + "Mapper")
            .replace('@entityPackage@', entityPackage + '.' + className)
            .replace('@mapperName@', className + 'Mapper')
            .replace('@entityName@', className)
            .replace('@serviceName@', className + 'Service')
            .replace('@Date@', new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
}

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


def calcFields(table) {
    primaryKey = getPrimaryKey(table)
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def entityName = javaName(col.getName(), false)
        def isPrimary = entityName.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        : entityName,
                           sqlFieldName: col.getName(),
                           isPrimary   : isPrimary,
                           commoent    : col.getComment(),
                           type        : typeStr
                ]
        ]
    }
}

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 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 = javaName(key, false);
        }
    }
    return key
}

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 + '''">
'''
}

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

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 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 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>
'''
}
posted @ 2022-01-06 14:45  GHzz  阅读(36)  评论(0编辑  收藏  举报