项目中通常会遇到数据的持久化,如果是采用mybatis的orm,就会涉及到生成xml的问题,刚好mybatis官网提供了这么个插件MyBatis Generator,效果简直是棒呆。
1. 首先需要在build.gradle文件中添加依赖


dependencies {
    compile('org.mybatis.generator:mybatis-generator-core:1.3.7')
}

2.在当前的项目中创建一个类,添加一个main方法,main方法内容如下:。

public class CustomMybatisGenerator {


    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");  //其中generaroeConfig.xml文件放到resources目录下即可
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }

}

3. 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>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/test"
                    userId="root"
                    password="password">
    </jdbcConnection>

    <javaModelGenerator targetPackage="test.model" targetProject="G:\MyProject\src\main\java"/>

    <sqlMapGenerator targetPackage="mapper"  targetProject="G:\MyProject\src\main\resources"/>

    <javaClientGenerator targetPackage="test.mapper" targetProject="G:\MyProject\src\main\java" type="XMLMAPPER" />

    <table tableName="%" >
      <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
    </table>
  </context>
</generatorConfiguration>

4. 此时运行就可以了。

04-24 10:21