Intellij IDEA 中结合 Gradle 使用 MyBatis Generator 逆向生成代码


title: Intellij IDEA 中结合 Gradle 使用 MyBatis Generator 逆向生成代码
date: 2016-04-26 18:17:26
categories: "Java"
tags:

  • MyBatis

在 Intellij IDEA 中结合 Gradle 使用 MyBatis Generator 逆向生成代码

  • JDK 1.8
  • Gradle 3.5
  • Intellij IDEA 2017

前言

Intellij IDEA 的教程较少,且 MyBatis Generator 不支持 Gradle 直接运行,因此这次是在自己折腾项目过程中,根据一些参考资料加上自己的实践得出的结论,并附上相应的 Demo 可供自己未来参考,也与大家分享。

本文的 Demo 也可以当作工具直接导入 IDEA,加上自己的数据库信息即可生成代码。

创建项目

创建步骤可以参考intellij idea 2016 gradle搭建web工程中。当创建完毕,需要等待 Gradle 联网构建,由于国内网络因素,可能需要稍作等待。当构建完成,目录结构应如下图一致:

step1.png

配置依赖

这里需要使用 MyBatis Generator,MySQL 驱动,以及 MyBatis Mapper。由于代码生成单独运行即可,不需要参与到整个项目的编译,因此在 build.gradle 中添加配置:

configurations {
mybatisGenerator
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'

mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.5'
mybatisGenerator 'mysql:mysql-connector-java:5.1.40'
mybatisGenerator 'tk.mybatis:mapper:3.3.9'
}

设置数据库信息

在 resources 下,新建 mybatis 文件夹,并新建 jdbc.properties 和 generatorConfig.xml,文件结构如下:

step2.png

在 config.properties 中配置数据库和要生成的 Java 类的包:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.11:3306/ssmDemo?characterEncoding=utf8
jdbc.username=root
jdbc.password=111111


# 生成实体类所在的包
package.model=org.zn.user.entity
# 生成 mapper 类所在的包
package.mapper=org.zn.user.dao
# 生成 mapper xml 文件所在的包,默认存储在 resources 目录下
package.xml=mapping
# 表名
package.tableName=user
# 生成实体类名称
package.entityName=User

设置生成代码的配置文件

在 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">
        <commentGenerator>
            <property name="suppressAllComments" value="true"></property>
            <property name="suppressDate" value="true"></property>
            <property name="javaFileEncoding" value="utf-8"/>
        </commentGenerator>

        <jdbcConnection driverClass="${driverClass}"
                        connectionURL="${connectionURL}"
                        userId="${userId}"
                        password="${password}">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}" targetProject="${src_main_java}">
            <property name="enableSubPackages" value="true"></property>
            <property name="trimStrings" value="true"></property>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="${sqlMapperPackage}" targetProject="${src_main_resources}">
            <property name="enableSubPackages" value="true"></property>
        </sqlMapGenerator>

        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
             type="MIXEDMAPPER",生成基于注解的JavaModel 和相应的Mapper对象
             type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口  -->
        <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${src_main_java}" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 这种方式是所有的表逆向生成类 下面是单个表具体看情况使用
        <table tableName="%">
            <generatedKey column="epa_id" sqlStatement="Mysql" identity="true" />
        </table> -->


        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="${tableName}" domainObjectName="${entityName}"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

Gradle 设置 Ant Task

由于 MyBatis Generator 尚不支持 Gradle,所以只能使用 Gradle 来执行 Ant Task,达到相同的效果。

build.gradle:

def getDbProperties = {
def properties = new Properties()
file("src/main/resources/jdbc.properties").withInputStream { inputStream ->
properties.load(inputStream)
}
properties
}

task mybatisGenerate << {
    def properties = getDbProperties()
    ant.properties['targetProject'] = projectDir.path
    ant.properties['driverClass'] = properties.getProperty("jdbc.driver")
    ant.properties['connectionURL'] = properties.getProperty("jdbc.url")
    ant.properties['userId'] = properties.getProperty("jdbc.username")
    ant.properties['password'] = properties.getProperty("jdbc.password")
    ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path
    ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path
    ant.properties['modelPackage'] = properties.getProperty("package.model")
    ant.properties['mapperPackage'] = properties.getProperty("package.mapper")
    ant.properties['sqlMapperPackage'] = properties.getProperty("package.xml")
    ant.properties['tableName'] = properties.getProperty("package.tableName")
    ant.properties['entityName'] = properties.getProperty("package.entityName")
    ant.taskdef(
            name: 'mbgenerator',
            classname: 'org.mybatis.generator.ant.GeneratorAntTask',
            classpath: configurations.mybatisGenerator.asPath
    )
    ant.mbgenerator(overwrite: true,
            configfile: 'src/main/resources/generatorConfig.xml', verbose: true) {
        propertyset {
            propertyref(name: 'targetProject')
            propertyref(name: 'userId')
            propertyref(name: 'driverClass')
            propertyref(name: 'connectionURL')
            propertyref(name: 'password')
            propertyref(name: 'src_main_java')
            propertyref(name: 'src_main_resources')
            propertyref(name: 'modelPackage')
            propertyref(name: 'mapperPackage')
            propertyref(name: 'sqlMapperPackage')
            propertyref(name: 'tableName')
            propertyref(name: 'entityName')
        }
    }
}

配置好 build.gradle,就可以在 IDEA 的 Gradle 菜单中找到新的 Task:

step3.png

如果这里没有,可能是 Gradle 没有 build,重新刷新即可:

step4.png

双击「mybatisGenerate」即可运行,如果配置正确即可运行成功:

step5.png

总结

感谢网上博友的无私奉献,参考你们的博文最终得以完成

Gradle+SSM+MyBatis Generator源码地址:https://github.com/enamor/ssm

原文地址: http://oxy.pub

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容