码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis的逆向工程

时间:2016-05-06 20:15:32      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:

所谓逆向工程就是由数据库表生成java代码。

主要的是mybatis提供的逆向工程的jar文件

mybatis-generator-core-1.3.2.jar

首先看一下完整的项目结构

技术分享

工具类

public class GeneratorSqlmap {
    
    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件,如果在项目文件夹下直接文件名就可以了
        File configFile = new File("config/generatorConfig.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);

    } 
    public static void main(String[] args) throws Exception {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}

配置文件

<?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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/taotao" userId="root"
            password="root">
        </jdbcConnection>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:自动生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.taotao.pojo"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.taotao.dao.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.taotao.dao.mapper" implementationPackage="com.taotao.dao"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <!-- 指定数据库表 -->
        <table schema="" tableName="tb_content"></table>
        <table schema="" tableName="tb_content_category"></table>
        <table schema="" tableName="tb_item"></table>
        <table schema="" tableName="tb_item_cat"></table>
        <table schema="" tableName="tb_item_desc"></table>
        <table schema="" tableName="tb_item_param"></table>
        <table schema="" tableName="tb_item_param_item"></table>
        <table schema="" tableName="tb_order"></table>
        <table schema="" tableName="tb_order_item"></table>
        <table schema="" tableName="tb_order_shipping"></table>
        <table schema="" tableName="tb_user"></table>


    </context>
</generatorConfiguration>

其实相关的内容在MyBatis Generator文档中有

下面摘录一部分

Running MyBatis Generator With Java

MyBatis Generator (MBG) may be invoked directly from Java. For configuration, you may use either an XML configuration file, or configure MBG completely with Java.

Running MBG from Java with an XML Configuration File

The following code sample shows how to call MBG from Java with an XML based configuration. It does not show exception handling, but that should be obvious from the compiler errors :)

//可以看到,这就是工具类中的代码
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.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);

Notes:

  • Configuration file properties may be passed to the parser as a parameter on the ConfigurationParser constructor. If not passed explicitly, the JVM system properties will be searched for the value of configuration file properties. For example, the property generated.source.dir can be accessed in the configuration file with the escape sequence ${generated.source.dir}
  • If a property is specified in the configuration file and is not resolved, then the escaped property string will be passed "as is" into the generated code.

Running MBG from Java with a Java Based Configuration

The following code sample shows how to call MBG from Java with a Java based configuration. It does not show exception handling, but that should be obvious from the compiler errors :)

   List<String> warnings = new ArrayList<String>();
   boolean overwrite = true;
   Configuration config = new Configuration();

   //   ... fill out the config object as appropriate...

   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
   myBatisGenerator.generate(null);

MyBatis GeneratorXML Configuration File Reference

In the most common use case, MyBatis Generator (MBG) is driven by an XML configuration file. The configuration file tells MBG:

  • How to connect to the database
  • What objects to generate, and how to generate them
  • What tables should be used for object generation

The following is an example MBG configuration file. See the individual pages for each element for more information about the elements and the values of the attributes.

<?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>
  <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />

  <context id="DB2Tables" targetRuntime="MyBatis3">
    <jdbcConnection driverClass="COM.ibm.db2.jdbc.app.DB2Driver"
        connectionURL="jdbc:db2:TEST"
        userId="db2admin"
        password="db2admin">
    </jdbcConnection>

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

    <javaModelGenerator targetPackage="test.model" targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="test.xml"  targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="test.dao"  targetProject="\MBGTestProject\src">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
      <property name="useActualColumnNames" value="true"/>
      <generatedKey column="ID" sqlStatement="DB2" identity="true" />
      <columnOverride column="DATE_FIELD" property="startDate" />
      <ignoreColumn column="FRED" />
      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
    </table>

  </context>
</generatorConfiguration>

Important notes about this file follow:

  • The file specifies that the legacy DB2 CLI driver will be used to connect to the database, and also specifies where the driver can be found.
  • The Java Type Resolver should not force the use of BigDecimal fields - this means that integral types (Short, Integer, Long, etc.) will be substituted if possible. This feature is an attempt to make database DECIMAL and NUMERIC columns easier to deal with.
  • The Java model generator should use sub-packages. This means that the generated model objects will be placed in a package called test.model.db2admin in this case (because the table is in the DB2ADMIN schema). If the enableSubPackages attribute was set to false, then the package would be test.model. The Java model generator should also trim strings. This means that the setters for any String properties will call the trim function - this is useful if your database might return blank characters at the end of character columns.
  • The SQL Map generator should use sub-packages. This means that the generated XML files will be placed in a package called test.xml.db2admin in this case (because the table is in the DB2ADMIN schema). If the enableSubPackages attribute was set to false, then the package would be test.xml.
  • The DAO generator should use sub-packages. This means that the generated DAO classes will be placed in a package called test.dao.db2admin in this case (because the table is in the DB2ADMIN schema). If the enableSubPackages attribute was set to false, then the package would be test.dao. The DAO generator should generate mapper interfaces that reference an XML configuration for MyBatis.
  • The file specifies only one table will be introspected, but many more could be specified. Important notes about the specified table include:
    • The generated objects will be based on the name Customer (CustomerKey, Customer, CustomerMapper, etc.) - rather than on the table name.
    • Actual column names will be used as properties. If this property were set to false (or not specified), then MBG would attempt to camel case the column names. In either case, the name can be overridden by the <columnOverride> element
    • The column has a generated key, it is an identity column, and the database type is DB2. This will cause MBG to generate the proper <selectKey> element in the generated <insert> statement so that the newly generated key can be returned (using DB2 specific SQL).
    • The column DATE_FIELD will be mapped to a property called startDate. This will override the default property which would be DATE_FIELD in this case, or dateField if the useActualColumnNames property was set to false.
    • The column FRED will be ignored. No SQL will list the field, and no Java property will be generated.
    • The column LONG_VARCHAR_FIELD will be treated as a VARCHAR field, regardless of the actual data type.

 

MyBatis的逆向工程

标签:

原文地址:http://www.cnblogs.com/winner-0715/p/5466886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!