利用mybatis generator生成實體類、Mapper接口以及對應的XML文件

項目中一般會遇到數據的持久化,若是是採用mybatis的orm,就會涉及到生成xml的問題,恰好mybatis官網提供了這麼個插件MyBatis Generator,效果簡直是棒呆。
1. 首先須要在build.gradle文件中添加依賴java

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

2.在當前的項目中建立一個類,添加一個main方法,main方法內容以下:。mysql

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文件sql

<?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. 此時運行就能夠了。數據庫

相關文章
相關標籤/搜索