美文网首页
gradle之MyBatis Generator生成model,

gradle之MyBatis Generator生成model,

作者: lmandy | 来源:发表于2018-05-15 15:00 被阅读0次

Mybatis Generator(http://mybatis.org/generator/index.html) 是一个Mybatis的代码生成器,它可以帮助我们根据数据库中表的设计生成对应的model,dao,xml文件及简单的crud sql。Mybatis Generator提供了maven plugin,ant targetjava三种方式启动。现在主流的构建工具是gradle和maven,虽然mybatis generator没有提供gradle的插件,但gradle可以调用ant任务,因此,gradle也能启动Mybatis Generator。下面我们介绍gradl中使用Mybatis Generator


一.环境准备

  1. 创建数据库user和表user_test,user_info
CREATE TABLE `user_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `pass_world` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
------------------------------------------------------------------------
CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
  1. 创建配置文件
  • jdbc.properties 数据库连接文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///user?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=123
  • gradle.properties 生成model,mapper,xml路径配置文件
#生成的实体路径
modelPackage=com.bean
# mapper路径
mapperPackage=com.mapper
#mapper.xml路径
sqlMapperPackage=com.mapper
  • 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">
        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
            <property name="caseSensitive" value="true"/>
        </plugin>
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="${driverClass}"
                        connectionURL="${connectionURL}"
                        userId="${userId}"
                        password="${password}">
        </jdbcConnection>
        <javaModelGenerator targetPackage="${modelPackage}" targetProject="${src_main_java}"/>
        <sqlMapGenerator targetPackage="${sqlMapperPackage}" targetProject="${src_main_resources}"/>
        <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${src_main_java}" type="XMLMAPPER"/>
        <!-- sql占位符,表示所有的表 -->
        <table tableName="%">
            <generatedKey column="epa_id" sqlStatement="Mysql" identity="true" />
        </table>
    </context>
</generatorConfiguration>

这里面用了通用mapper组件如果不想用,就将上述文件中下面的注释

<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
            <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
          <property name="caseSensitive" value="true"/>
</plugin>
  • build.gradle ssm配置和myabtis生成器配置
group 'com'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8

repositories {
    maven{
        url "http://maven.aliyun.com/nexus/content/repositories/central/"
    }
}

configurations {
    mybatisGenerator
}

dependencies {

    //junit 单元测试
    testCompile group: 'junit', name: 'junit', version: '4.11'
    //sping
    compile group: 'org.springframework', name: 'spring-core', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-context', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-beans', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-expression', version: '4.3.6.RELEASE'

    compile group: 'org.springframework', name: 'spring-context-support', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-web', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.6.RELEASE'

    compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-aop', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-tx', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-orm', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-test', version: '4.3.6.RELEASE'
    compile group: 'org.springframework', name: 'spring-aspects', version: '4.3.6.RELEASE'

//  spring依赖日志包
    compile group: 'commons-logging', name: 'commons-logging', version: '1.2'

//  string 增强
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4'
//  集合增强
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2.1'
//上传组件
    compile group: 'commons-io', name: 'commons-io', version: '2.4'
    compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'
    compile group: 'commons-codec', name: 'commons-codec', version: '1.10'
//mybatis及依赖包
    compile group: 'org.mybatis', name: 'mybatis', version: '3.4.2'
//spring 整合 mybatis
    compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.0'
//dbcp 连接池配置数据库
    compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'
//jsp相关
    compile group: 'jstl', name: 'jstl', version: '1.2'
//JavaEE servlet
    compile group: 'javax', name: 'javaee-api', version: '7.0'

//日志
    compile group: 'log4j', name: 'log4j', version: '1.2.17'
    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.24'
    compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.24'
//gson
    compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
//fastjson
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.33'
//shiro
    compile group: 'org.apache.shiro', name: 'shiro-core', version: '1.3.2'
    compile group: 'org.apache.shiro', name: 'shiro-web', version: '1.3.2'
    compile group: 'org.apache.shiro', name: 'shiro-spring', version: '1.3.2'
    compile group: 'org.apache.shiro', name: 'shiro-ehcache', version: '1.3.2'
//通用mapper
    compile group: 'tk.mybatis', name: 'mapper', version: '3.4.2'

//生成器依赖
    mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.2'
    mybatisGenerator 'mysql:mysql-connector-java:5.1.36'
    mybatisGenerator 'tk.mybatis:mapper:3.4.2'
}
//添加 ant 任务
def getDbProperties = {
    def dDProperties = new Properties()
    file("src/main/resources/jdbc.properties").withInputStream { inputStream ->
        dDProperties.load(inputStream)
    }
    dDProperties;
}
def getGradleProperties = {
    def gradleProperties = new Properties()
    file("src/main/resources/gradle.properties").withInputStream { inputStream ->
        gradleProperties.load(inputStream)
    }
    gradleProperties;
}
task mybatisGenerate << {
    def dDProperties = getDbProperties()
    def gradleProperties = getGradleProperties()
    ant.properties['targetProject'] = projectDir.path
    ant.properties['driverClass'] = dDProperties.getProperty("jdbc.driver")
    ant.properties['connectionURL'] = dDProperties.getProperty("jdbc.url")
    ant.properties['userId'] = dDProperties.getProperty("jdbc.username")
    ant.properties['password'] = dDProperties.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'] = gradleProperties.getProperty("modelPackage")
    ant.properties['mapperPackage'] =  gradleProperties.getProperty("mapperPackage")
    ant.properties['sqlMapperPackage'] =  gradleProperties.getProperty("sqlMapperPackage")
    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')
        }
    }
}

二. 运行,生成文件到指定目录

image.png

三.生成指定的表

在这里我指定生成user_info 这张表

  • 在gradle.properties 加入指定生成表名和对应生成的className名称


    image.png
#生成指定表
tableName = user_info
#生成指定表对应的className
domainObjectName = UserInfo
  • 在build.gradle文件中加入刚刚的配置


    image.png
  • 更改generatorConfig.xml 将默认生成所有表改成指定表,此文件中表变量值取的是build.gradle文件中task中的变量,请保持一致。

    image.png
    至此完结,点击运行,大功告成
    demo地址 https://github.com/lmandy/Gradle-MybatisGenerator
  • 注意:如果在generator.xml中没有使用 通用mapper 组件
    那么在配置dao接口扫描时下面改成对应的扫描器


    image.png

四.引用

(generatorConfig.xml配置文件详解)
https://www.jianshu.com/p/e09d2370b796
https://www.jianshu.com/p/5c85becf5f73

相关文章

网友评论

      本文标题:gradle之MyBatis Generator生成model,

      本文链接:https://www.haomeiwen.com/subject/rxyedftx.html