idea + groovy + mybatis 自动生成 Dao、mappings 和 实体类

  • Post author:
  • Post category:其他


背景

在 windows 系统中,idea 在

C:\Users\用户名\.IntelliJIdea2018.2\config\extensions\com.intellij.database\schema

目录下默认存在如下 Groovy 文件:

Generate POJOs.groovy

,配合 idea 的 Database 数据库管理工具,可以快速生成 POJO 类。

于是我想何不基于这个类编写 groovy 代码自动生成 mappings 和 dao 呢,并按自己项目需要改造

Generate POJOs.groovy

Groovy

groovy 是在 java 平台上的、具有象 Python,Ruby 和 Smalltalk 语言特性的灵活动态语言,groovy 保证了这些

特性象 java 语法一样被 java 开发者使用。 — 《Groovy in action》

Groovy 跟 java 一样是运行于 JVM 之上的语言,比起 java 拥有许多语法上的便利,可以无缝使用 java 类库及其特性,甚至可以直接用 Groovy 开发 Web 程序。

实现

无论是修改

Generate POJOs.groovy

还是在其基础之上编写新的 groovy 文件都需要将其放于

C:\Users\用户名\.IntelliJIdea2018.2\config\extensions\com.intellij.database\schema

目录下,这样文件中引入的

com.intellij.database.*

才能找到,新建 idea 项目也会在 Scratches and Consoles 目录下找到。

连接数据库

打开项目:

1、点击右侧的datesource图标,要是没有该图标,请去自行百度

2、点击 + 号

3、选择 datasource

4、选择 mysql

1、填写一个连接名,随便填什么都行

2、不用选择,默认就行

3、填写数据库连接的 IP地址,比如本地数据库可以填写:localhost或者127.0.0.1

4、填写数据库开放的端口号,一般没设置的话默认都是3306

5、填写你需要连接的数据库名

6、填写数据库的用户名

7、填写数据库密码

8、这里会有一个驱动需要点击下载,图中是已经下载好了

9、填写自己的数据库连接url,然后可以点击9所在按钮进行测试连接,本地连接失败检查是否开启了mysql服务

连接好了如上图所示,可以看到自己的数据库和表,选择一个表右键

Generate MyPOJOs.groovy文件(生成实体类):

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.io.*
import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
packageName = "com.gx.entity"
typeMapping = [

        (~/(?i)bigint/)      : "Long",
        (~/(?i)smallint|mediumint|tinyint|int/)      : "Integer",
        (~/(?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 && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
    //def className = javaClassName(table.getName(), true)
    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)}

//    new File(dir, className + ".java").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) {
    def tableName = table.getName()
    out.println "package $packageName"
    out.println ""
    out.println "import javax.persistence.*;"
    /*out.println "import javax.persistence.Entity;"
    out.println "import javax.persistence.Table;"*/
    out.println "import java.io.Serializable;"
    out.println "import lombok.Data;"
    /*out.println "import lombok.AllArgsConstructor;"
    out.println "import lombok.Builder;"
    out.println "import lombok.NoArgsConstructor;"*/

    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  GX\n" +
            " * @Date "+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
            " */"
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table ( name =\""+table.getName() +"\" )"
    out.println "public class $className  implements Serializable {"
    out.println genSerialID()


    // 判断自增
    /*if ((tableName + "_id").equalsIgnoreCase(fields[0].colName) || "id".equalsIgnoreCase(fields[0].colName)) {
        out.println "\t@Id"
        out.println "\t@GeneratedValue(generator = \"idGenerator\")"
        out.println "\t@GenericGenerator(name = \"idGenerator\", strategy = ChiticCoreConstant.ID_GENERATOR_COMMON)"
    }*/


    fields.each() {
        out.println ""
        // 输出注释
        if (isNotEmpty(it.commoent)) {
            out.println "\t/**"
            out.println "\t * ${it.commoent.toString()}"
            out.println "\t */"
        }

        if (it.annos != ""){
            if (it.annos.contains("[@Id]")){
                out.println "\t@Id"
                out.println "\t@GeneratedValue(generator = \"idGenerator\")"
                out.println "\t@GenericGenerator(name = \"idGenerator\", strategy = ChiticCoreConstant.ID_GENERATOR_COMMON)"
            }
            out.println "   ${it.annos.replace("[@Id]", "")}"
        }


        // 输出成员变量
        out.println "\tprivate ${it.type} ${it.name};"
    }

    // 输出get/set方法
//    fields.each() {
//        out.println ""
//        out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
//        out.println "\t\treturn this.${it.name};"
//        out.println "\t}"
//        out.println ""
//
//        out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
//        out.println "\t\tthis.${it.name} = ${it.name};"
//        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]
    }
}

// 处理类名(这里是因为我的表都是以t_命名的,所以需要处理去掉生成类名时的开头的T,
// 如果你不需要那么请查找用到了 javaClassName这个方法的地方修改为 javaName 即可)
def javaClassName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    // 去除开头的T  http://developer.51cto.com/art/200906/129168.htm
    s = s[1..s.size() - 1]
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def javaName(str, capitalize) {
//    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
//            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
//    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
    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('')
    }
}

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

Generate Dao.groovy文件(生成dao):

package src

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

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

packageName = "**;" // 需手动配置 生成的 dao 所在包位置

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 baseName = javaName(table.getName(), true)
    new File(dir, baseName + "Mapper.java").withPrintWriter { out -> generateInterface(out, baseName) }
}

def generateInterface(out, baseName) {
    def date = new Date().format("yyyy/MM/dd")
    out.println "package $packageName"
    out.println "import cn.xx.entity.${baseName}Entity;" // 需手动配置
    out.println "import org.springframework.stereotype.Repository;"
    out.println ""
    out.println "/**"
    out.println " * Created on $date."
    out.println " *"
    out.println " * @author GX" // 可自定义
    out.println " */"
    out.println "@Repository"
    out.println "public interface ${baseName}Dao extends BaseDao<${baseName}Entity> {" // 可自定义
    out.println ""
    out.println "}"
}

def javaName(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]
}

复制代码

Generate DaoXml.groovy文件(生成dao.xml):

复制代码

package src

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

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

// entity(dto)、mapper(dao) 与数据库表的对应关系在这里手动指明,idea Database 窗口里只能选下列配置了的 mapper
// tableName(key) : [mapper(dao),entity(dto)]
typeMapping = [
        (~/(?i)int/)                      : "INTEGER",
        (~/(?i)float|double|decimal|real/): "DOUBLE",
        (~/(?i)datetime|timestamp/)       : "TIMESTAMP",
        (~/(?i)date/)                     : "TIMESTAMP",
        (~/(?i)time/)                     : "TIMESTAMP",
        (~/(?i)/)                         : "VARCHAR"
]

basePackage = "com.chitic.bank.mapping" // 包名需手动填写

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 baseName = mapperName(table.getName(), true)
    def fields = calcFields(table)
    new File(dir, baseName + "Mapper.xml").withPrintWriter { out -> generate(table, out, baseName, fields) }
}

def generate(table, out, baseName, fields) {
    def baseResultMap = 'BaseResultMap'
    def base_Column_List = 'Base_Column_List'
    def date = new Date().format("yyyy/MM/dd")
    def tableName = table.getName()

    def dao = basePackage + ".dao.${baseName}Mapper"
    def to = basePackage + ".to.${baseName}TO"

    out.println mappingsStart(dao)
    out.println resultMap(baseResultMap, to, fields)
    out.println sql(fields, base_Column_List)
    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()

}

static def resultMap(baseResultMap, to, fields) {

    def inner = ''
    fields.each() {
        inner += '\t\t<result column="' + it.sqlFieldName + '" jdbcType="' + it.type + '" property="' + it.name + '"/>\n'
    }

    return '''\t<resultMap id="''' + baseResultMap + '''" type="''' + to + '''">
        <id column="id" jdbcType="INTEGER" property="id"/>
''' + inner + '''\t</resultMap>
'''
}

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 += [[
                           comment     : col.getComment(),
                           name        : mapperName(col.getName(), false),
                           sqlFieldName: col.getName(),
                           type        : typeStr,
                           annos       : ""]]
    }

}

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, base_Column_List) {
    def str = '''\t<sql id="''' + base_Column_List + '''">
        @inner@
    </sql> '''

    def inner = ''
    fields.each() {
        inner += ('\t\t' + 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 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
}


jpa的

Repository

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

packageName = "com.gx.dao;"
packageEntityName = "com.gx.entity"

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 entityName = javaName(table.getName(), true)
    def className = entityName + "Repository"
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, table, className, entityName) }
}

def generate(out, table, className, entityName) {
    out.println "package $packageName"
    out.println ""
    out.println "import org.springframework.stereotype.Repository;"
    out.println "import org.springframework.data.jpa.repository.JpaRepository;"
    out.println "import org.springframework.data.jpa.repository.JpaSpecificationExecutor;"
    out.println ""
    out.println "import $packageEntityName.$entityName;"
    out.println ""
    out.println "@Repository"
    out.println "public interface $className extends JpaRepository<$entityName, Long>, JpaSpecificationExecutor<$entityName> {"
    out.println ""
    out.println "}"
}

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



版权声明:本文为adparking原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。