MyBatis 逆向工程

1. MyBatis Generator

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

2. 环境搭建

// 在项目下创建 mbg.xml(具体见"参考资料")

<generatorConfiguration>

  <!--
        targetRuntime="MyBatis3Simple": 生成简单版的CRUD
        targetRuntime="MyBatis3": 生成复杂的 CRUD
  -->
  <context id="DB2Tables" targetRuntime="MyBatis3">

    <!-- jdbcConnection: 指定如何连接到目标数据库 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis"
        userId="root"
        password="root">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!-- javaModelGenderator: 指定javaBean的生成策略 -->
    <javaModelGenerator targetPackage="cn.itcast.mybatis.bean" targetProject="./src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- sqlMapGenerator: sql 映射生成策略 -->
    <sqlMapGenerator targetPackage="cn.itcast.mybatis.dao"  targetProject="./conf">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- 指定mapper接口所在位置 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="cn.itcast.mybatis.dao"  
                                                                        targetProject="./src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 指定要逆向分析哪些表,根据这些表,创建 javaBean -->
    <table tableName="tbl_dept" domainObjectName="Department"></table>
    <table tableName="tbl_employee" domainObjectName="Employee"></table>
  </context>
</generatorConfiguration>

// 编写测试类
public class MyBatisTest{

    // 运行MBG
    @Test
    public void testMbg() throws IOException, XMLParsetException, InvalidConfiguration,
                                            SQLException,InterruptedException{

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

参考资料

原文地址:https://www.cnblogs.com/linkworld/p/7798101.html