Gradle项目使用MyBatis-generator自动生成MyBatis映射代码
目录
引用:
Maven库 (PS: 找jar包,用它基本就够了,当然前提是知道哪个jar包,比如ant包)
dependency.gradle:
//统一依赖定义
ext.libraries = [
mybatisGenerators: [
'org.mybatis.generator:mybatis-generator-core:1.4.0',
'mysql:mysql-connector-java:5.1.48',
'org.mybatis:mybatis:3.5.1',
'org.apache.ant:ant:1.10.5'
]
] buidle.gradle 添加dependecy.gradle的引用
apply from: 'dependency.gradle'
1,方式一:使用类 MyBatisGenerator
准备的xml: 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="context" targetRuntime="MyBatis3">
<!--覆盖生成XML文件 -->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库的相关配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/yan?useSSL=false" userId="yan" password="yan.123"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 实体类生成的位置 -->
<javaModelGenerator targetPackage="com.report.entity.po" targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- *Mapper.xml 文件的位置 -->
<sqlMapGenerator targetPackage="report" targetProject=".\src\main\resources\mybatis">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- Mapper 接口文件的位置 -->
<javaClientGenerator targetPackage="com.report.repository" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 相关表的配置 -->
<table tableName="sys_report_class" domainObjectName="SysReportClass" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
<table tableName="sys_report_param" domainObjectName="SysReportParam" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
</context>
</generatorConfiguration>
<plugintype="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
注意:使用类生成的时候,要添加这个,不然会追加生成
类:MybatisGeneratorUtil
public class MybatisGeneratorUtil {
public static void main(String[] args) {
generateMybatisInfo();
}
private static void generateMybatisInfo() {
try {
System.out.println("start generator ...");
List<String> warnings = new ArrayList<>();
File configFile = new File("src/main/resources/mybatis/config/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println("end generator!");
} catch (IOException | XMLParserException | InterruptedException | SQLException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
2,使用build任务生成:
Xml:generatorConfigMb.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="context" targetRuntime="MyBatis3">
<!--覆盖生成XML文件 使用gradle任务的方式会读取不到-->
<!--<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库的相关配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/yan?useSSL=false" userId="yan" password="yan.123"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 实体类生成的位置 -->
<javaModelGenerator targetPackage="com.report.entity.po" targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- *Mapper.xml 文件的位置 -->
<sqlMapGenerator targetPackage="report" targetProject=".\src\main\resources\mybatis">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- Mapper 接口文件的位置 -->
<javaClientGenerator targetPackage="com.report.repository" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 相关表的配置 -->
<table tableName="sys_report_class" domainObjectName="SysReportClass" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
<table tableName="sys_report_param" domainObjectName="SysReportParam" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
</context>
</generatorConfiguration>
注意: 使用任务的生成的方式,不会覆盖。
<!--<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />-->
这边就注释了。不然会报找不到的错误
Build.gradle:
plugins {
id "com.arenagod.gradle.MybatisGenerator" version "1.4" //gradle提供的mybatis generator插件
}
mybatisGenerator {
verbose = true
configFile = 'src/main/resources/mybatis/config/generatorConfigMb.xml'
}
点击更新,然后点击:mbGenerator

生成结果:

3.使用ant的方式:
1,GeneratorAntTask
Xml: generatorConfig.xml 同方法一的xml
类:MybatisAntGeneratorUtil
public class MybatisAntGeneratorUtil {
public static void main(String[] args) {
generateMybatisXml();
}
public static void generateMybatisXml() {
try {
System.out.println("start mybatis generator ...");
GeneratorAntTask task = new GeneratorAntTask();
String xmlPath = "D:/project/report/src/main/resources/mybatis/config/generatorConfig.xml";
task.setConfigfile(xmlPath); //(配置文件具体path)
task.execute();
System.out.println("end mybatis generator!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用类GeneratorAntTask必须要引用 ant的包: 'org.apache.ant:ant:1.10.5'
2,使用build任务ant方式(失败)
Builde.gradle:
plugins {
id "com.arenagod.gradle.MybatisGenerator" version "1.4" //gradle提供的mybatis generator插件
}
def getDbProperties = {
def properties = new Properties()
file("src/main/resources/mybatis/config/jdbc.properties").withInputStream { inputStream ->
properties.load(inputStream)
}
properties
}
task mybatisGenerate << {
def properties = getDbProperties()
ant.properties['targetProject'] = projectDir.path
ant.properties['driverClass'] = properties.getProperty("jdbc.driverClassName")
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("modelPackage")
ant.properties['mapperPackage'] = properties.getProperty("mapperPackage")
ant.properties['sqlMapperPackage'] = properties.getProperty("sqlMapperPackage")
ant.taskdef(
name: 'mybatisGenerator',
classname: 'org.mybatis.generator.ant.GeneratorAntTask',
classpath: configurations.mybatisGenerator.asPath
)
ant.mybatisGenerator(overwrite: true,
configfile: 'src/main/resources/mybatis/config/generator-config.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')
}
}
}
数据库文件:jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/yan?useSSL=false
jdbc.username=yan
jdbc.password=yan.123
jdbc.driverClassName=com.mysql.jdbc.Driver
#生成实体类所在的包
modelPackage=com.ffcs.iod.ms.workflow.report.entity
#生成的mapper接口类所在包
mapperPackage=com.ffcs.iod.ms.workflow.report.repository
#生成的mapper xml文件所在包,默认存储在resources目录下
sqlMapperPackage=src/main/resources/mybatis/report xml 文件:generator-config.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="context" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
<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>
<!-- *Mapper.xml 文件的位置 -->
<sqlMapGenerator targetPackage="${sqlMapperPackage}" targetProject="${src_main_resources}">
<property name="enableSubPackages" value="true"></property>
</sqlMapGenerator>
<!-- Mapper 接口文件的位置 -->
<!--
type=ANNOTATEDMAPPER表示不生成xml文件
这里我用XMLMAPPER
-->
<javaClientGenerator targetPackage="${mapperPackage}" targetProject="${src_main_java}" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 相关表的配置 -->
<table tableName="sys_report_class" domainObjectName="SysReportClass" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
<table tableName="sys_report_param" domainObjectName="SysReportParam" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
</context>
</generatorConfiguration> 刷新项目并执行:

报错:
* What went wrong:
Execution failed for task ':mybatisGenerate'.
> taskdef class org.mybatis.generator.ant.GeneratorAntTask cannot be found
using the classloader AntClassLoader[]
网上查了下,没找到解决方式就放弃了。这种方式还麻烦。
总结:
使用方法2最简单,方法1会简单些,方法3还有引用ant的jar包。 方式4网上很多案例都是那样,但是报错了,后面有机会碰到再更新。
使用mybatis-generator生成,减少一些工作。