gradle-generator自动生成代码的两种方式

本文介绍了使用Gradle结合Ant任务和Mybatis插件两种方式来自动化生成代码。通过在build.gradle中配置相关脚本,分别展示了如何利用generator.gradle文件和MybatisGenerator插件读取配置并生成代码。尽管两种方法都能实现功能,但文章推荐使用Mybatis插件,因为它代码简洁、配置更方便。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:利用ant

文件结构预览图:

在build.gradle文件中引入如下代码:

configurations{
    mybatisGenerator
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.mybatis', name: 'mybatis', version: '3.5.1'
    
    mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.7'
    mybatisGenerator 'tk.mybatis:mapper:4.0.3'
    mybatisGenerator 'mysql:mysql-connector-java:5.1.46'
}

apply from: "generator.gradle"

将generator.gradle文件apply加入build.gradle中,generator.gradle全代码如下:

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

task mybatisGenerate <<  {
    def dbProperties = getDbProperties()
    ant.properties['targetProject'] = projectDir.path
    ant.properties['jdbc_driver'] = dbProperties.getProperty("jdbc_driver")
    ant.properties['jdbc_url'] = dbProperties.getProperty("jdbc_url")
    ant.properties['jdbc_user'] = dbProperties.getProperty("jdbc_user")
    ant.properties['jdbc_password'] = dbProperties.getProperty("jdbc_password")
    //ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path  
    ant.properties['src_main_java'] = dbProperties.getProperty("project")
    //ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path  
    ant.properties['src_main_resources'] = dbProperties.getProperty("resources")
    ant.properties['modelPackage'] = dbProperties.getProperty("package_model")
    ant.properties['mapperPackage'] = dbProperties.getProperty("package_mapper")
    ant.properties['sqlMapperPackage'] = dbProperties.getProperty("package_xml")

    ant.taskdef(
            name: 'mbgenerator',
            classname: 'org.mybatis.generator.ant.GeneratorAntTask',
            classpath: configurations.mybatisGenerator.asPath
    )

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值