MyBatis框架

第7章:MyBatis 逆向工程

7.1 逆向工程简介

  • MyBatis Generator: 简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写

官方文档地址

http://www.mybatis.org/generator/

官方工程地址

https://github.com/mybatis/generator/releases

7.2 逆向工程的配置

  • 导入逆向工程的jar包

mybatis-generator-core-1.3.2.jar

  • 编写MBG的配置文件(重要几处配置),可参考官方手册

<?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>

  <!--

                targetRuntime: 执行生成的逆向工程的版本

                                  MyBatis3Simple: 生成基本的CRUD

                                  MyBatis3: 生成带条件的CRUD

   -->

  <context id="DB2Tables" targetRuntime="MyBatis3">

 

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"

        connectionURL="jdbc:mysql://localhost:3306/mybatis_1129"

        userId="root"

        password="1234">

    </jdbcConnection>

         <!-- javaBean的生成策略-->

    <javaModelGenerator targetPackage="com.atguigu.mybatis.beans" targetProject=".\src">

      <property name="enableSubPackages" value="true" />

      <property name="trimStrings" value="true" />

    </javaModelGenerator>

         <!-- SQL映射文件的生成策略 -->

    <sqlMapGenerator targetPackage="com.atguigu.mybatis.dao"  targetProject=".\conf">

      <property name="enableSubPackages" value="true" />

    </sqlMapGenerator>

 

         <!-- Mapper接口的生成策略 -->

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.dao"  targetProject=".\src">

      <property name="enableSubPackages" value="true" />

    </javaClientGenerator>

         <!-- 逆向分析的表 -->

    <table tableName="tbl_dept" domainObjectName="Department"></table>

    <table tableName="tbl_employee" domainObjectName="Employee"></table>

  </context>

</generatorConfiguration>

 

  • 运行代码生成器生成代码

         @Test

public void testMBG() throws Exception {

                      List<String> warnings = new ArrayList<String>();

                      boolean overwrite = true;

                      File configFile = new File("mbg.xml");

                      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);

}