gradle插件 mybatis Generator

相信很多人都喜欢用mybatis作为ORM框架,我也不例外,但是mybatis相比于spring-data-jap多了mapper.xml.而如果手工编写mapper.xml是很费时费力的一件事,所以mybatis官方出了mybatis Generator这款工具,用来自动生成mapper.xml和数据库实体,还有官方的maven插件。但是笔者是使用的是Gradle构建工具,官方并没有提供Gradle插件,所有笔者就编写了一个mybatis Generator的Gradle插件

创建Module

  • 首先在项目中新建一个module,项目类型可以选择为groovy,module的目录文件夹名字必须为buileSrc,在buileSrc目录下的build.gradle文件中添加如下代码

    apply plugin: 'groovy'
    apply plugin: 'maven'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile gradleApi()
        compile localGroovy()
        compile("org.mybatis.generator:mybatis-generator-core:1.3.5")
        compile("mysql:mysql-connector-java:5.1.39")
        compile("tk.mybatis:mapper-spring-boot-starter:1.1.1")
    }
    
  • 在buildSrc目录下分别创建如下目录

    src/main/groovy
    src/main/resources/META-INF/gradle-plugins/${插件名}.properties
    
  • 然后在${插件名}.properties中添加如下代码,value为插件类的全限定名

    implementation-class=cn.dysania.GeneratorPlugin
    

笔者的目录结构是如图所示

编写插件

  • 新建一个groovy类 实现Plugin接口,代码如下所示

    package cn.dysania
    
    import org.gradle.api.Plugin
    import org.gradle.api.Project
    import org.mybatis.generator.api.MyBatisGenerator
    import org.mybatis.generator.config.xml.ConfigurationParser
    import org.mybatis.generator.internal.DefaultShellCallback
    
    /**
     * Created by LiangT on 2017/8/4.
     */
    class GeneratorPlugin implements Plugin<Project> {
    
        @Override
        void apply(Project project) {
            def task = project.task('generator')
    
            def projectPath = project.projectDir.toString() + "\\src\\main\\"
            def configPath = projectPath + "resources\\generatorConfig.xml"
    
            task.getInputs().file(configPath)
    
            task.outputs.upToDateWhen({true})
    
            task.doFirst {
                def warnings = new ArrayList<>()
                def overwrite = true
                def cp = new ConfigurationParser(warnings)
                def config = cp.parseConfiguration(new File(configPath))
                config.getContexts().forEach({ context ->
                    context.javaClientGeneratorConfiguration.targetProject = projectPath + "java"
                    context.sqlMapGeneratorConfiguration.targetProject = projectPath + "resources"
                    context.javaModelGeneratorConfiguration.targetProject = projectPath + "java"
                })
                def callback = new DefaultShellCallback(overwrite)
                def myBatisGenerator = new MyBatisGenerator(config, callback, warnings)
                myBatisGenerator.generate(null)
            }
        }
    }
    
  • 此插件默认读取需要自动生成代码所在项目resources目录下的generatorConfig.xml文件 配置信息如下所示

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
    
        <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
            <property name="beginningDelimiter" value="`"/>
            <property name="endingDelimiter" value="`"/>
            <property name="javaFileEncoding" value="UTF-8"/>
    
            <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
                <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            </plugin>
    
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://127.0.0.1:3306/database?useUnicode=true&amp;characterEncoding=utf-8"
                            userId="root"
                            password="123456">
            </jdbcConnection>
    
            <javaModelGenerator targetPackage="cn.dysania.user.model" targetProject="user-server"/>
    
            <sqlMapGenerator targetPackage="mapper" targetProject="user-server"/>
    
            <javaClientGenerator targetPackage="cn.dysania.user.mapper" targetProject="user-server"
                                 type="XMLMAPPER"/>
    
            <table tableName="lottery_log">
                <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
            </table>
        </context>
    </generatorConfiguration>
    
  • 有关generatotConfig.xml的详细配置说明可以查看generator官网文档

使用

在需要自动生成代码的module的build.gradle文件中加入以下代码

apply plugin: "${插件名}"

然后运行 gradle generator 即可