Administrator
发布于 2023-01-05 / 76 阅读
0
0

Mybatis Generator Theory

Official Doc Site

https://mybatis.org/generator/

MyBatis Generator Quick Start Guide

refer to : https://mybatis.org/generator/quickstart.html

MyBatis Generator (MBG) generates code in different styles depending on how it is configured. This is controlled by specifying the targetRuntime attribute on a <context> configuration element. The table below summarizes the different options.

To get up and running quickly with MyBatis Generator (MBG), follow these steps:

  1. Create and fill out a configuration file appropriately (see below for samples)

  2. Save the file in some convenient location (like \temp\generatorConfig.xml)

  3. Run MBG from the command line with a command like this:

          java -jar mybatis-generator-core-x.x.x.jar -configfile \temp\generatorConfig.xml -overwrite
        
    

    This will tell MBG to run using your configuration file. It will also tell MBG to overwrite any existing Java or Kotlin files with the same name. If you want to save any existing files, then omit the -overwrite parameter. If there is a conflict, MBG will save the newly generated file with a unique name (e.g. MyClass.java.1).

  4. After running MBG, you will need to create or modify the standard MyBatis configuration make use of your newly generated code. See the Tasks After Running MyBatis Generator page for more information.

Target Runtime Information and Samples

Target Runtime Comments Sample Configuration
MyBatis3DynamicSql This is the default valueGenerates Java codeDoes not generate XML - MyBatis3 annotations are used exclusivelyThe generated model objects are “flat” - there is no separate primary key objectThe generated code is dependent on the MyBatis Dynamic SQL LibraryThe amount of generated code is relatively smallThe generated code allows tremendous flexibility in query construction Sample Configuration
MyBatis3Kotlin Generates Kotlin codeDoes not generate XML - MyBatis3 annotations are used exclusivelyThe generated model objects are “flat” - there is no separate primary key objectThe generated code is dependent on the MyBatis Dynamic SQL LibraryThe amount of generated code is relatively smallThe generated code allows tremendous flexibility in query construction Sample Configuration
MyBatis3 This is the original runtime. Before version 1.3.6 of MBG, most usages of MBG used this style of code.Generates Java codeGenerates MyBatis3 compatible XML and SQL or MyBatis3 compatible annotated interfaces with no XMLThe generated model objects may have a hierarchy with separate primary key objects and/or separate object with BLOB fieldsThe generated code has no external dependenciesThe amount of generated code is very largeThe generated code has limited capabilities for query construction and is difficult to extend Sample Configuration
MyBatis3Simple This is a simplified version of the MyBatis3 runtime.Generates Java codeGenerates MyBatis3 compatible XML and SQL or MyBatis3 compatible annotated interfaces with no XMLThe generated model objects are “flat” - there is no separate primary key objectThe generated code has no external dependenciesThe amount of generated code is relatively smallNo “by example” or “selective” methods are generatedThe generated code does not include methods for dynamic query construction and is difficult to extend Sample Configuration

Sample Configuration for MyBatis3DynamicSql

<!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="dsql" targetRuntime="MyBatis3DynamicSql">
    <jdbcConnection driverClass="org.hsqldb.jdbcDriver"
        connectionURL="jdbc:hsqldb:mem:aname" />

    <javaModelGenerator targetPackage="example.model" targetProject="src/main/java"/>

    <javaClientGenerator targetPackage="example.mapper" targetProject="src/main/java"/>

    <table tableName="FooTable" />
  </context>
</generatorConfiguration>

Sample Configuration for MyBatis3Kotlin

<!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="kotlin" targetRuntime="MyBatis3Kotlin">
    <jdbcConnection driverClass="org.hsqldb.jdbcDriver"
        connectionURL="jdbc:hsqldb:mem:aname" />

    <javaModelGenerator targetPackage="example.model" targetProject="src/main/kotlin"/>

    <javaClientGenerator targetPackage="example.mapper" targetProject="src/main/kotlin"/>

    <table tableName="FooTable" />
  </context>
</generatorConfiguration>

Sample Configuration for MyBatis3

<!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="simple" targetRuntime="MyBatis3">
    <jdbcConnection driverClass="org.hsqldb.jdbcDriver"
        connectionURL="jdbc:hsqldb:mem:aname" />

    <javaModelGenerator targetPackage="example.model" targetProject="src/main/java"/>

    <sqlMapGenerator targetPackage="example.mapper" targetProject="src/main/resources"/>

    <javaClientGenerator type="XMLMAPPER" targetPackage="example.mapper" targetProject="src/main/java"/>

    <table tableName="FooTable" />
  </context>
</generatorConfiguration>

Sample Configuration for MyBatis3Simple

<!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="simple" targetRuntime="MyBatis3Simple">
    <jdbcConnection driverClass="org.hsqldb.jdbcDriver"
        connectionURL="jdbc:hsqldb:mem:aname" />

    <javaModelGenerator targetPackage="example.model" targetProject="src/main/java"/>

    <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="example.mapper" targetProject="src/main/java"/>

    <table tableName="FooTable" />
  </context>
</generatorConfiguration>

Running MyBatis Generator

refer to : https://mybatis.org/generator/running/running.html

Important: When running outside of an IDE environment like Eclipse, MBG interprets the targetProject and targetPackage attributes in all XML configurations as follows:

  • targetProject is assumed to be an existing directory structure. MBG will fail if this directory structure does not exist. There is one exception to this rule - when MBG is running through the Maven plugin. See the Maven plugin page for information about how targetProject is interpreted in Maven.
  • targetPackage will be translated to a suitable subdirectory structure of the targetProject directory structure. MBG will create these subdirectories if necessary.

Running MyBatis Generator With Maven

refer to : https://mybatis.org/generator/running/runningWithMaven.html

MyBatis Generator (MBG) includes a Maven plugin for integration into a maven build. In keeping with Maven’s configuration by convention strategy, including MBG in a Maven build can be very simple. The minimum configuration is shown below:

   <project ...>
     ...
     <build>
       ...
       <plugins>
        ...
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.4.1</version>
        </plugin>
        ...
      </plugins>
      ...
    </build>
    ...
  </project>

Of course, things are never that easy!

Maven Goal and Execution

The MBG Maven plugin includes one goal:

  • mybatis-generator:generate

The goal is not automatically executed by Maven. It can be executed in two ways.

The goal can be executed from the command line with the command:

  • mvn mybatis-generator:generate

You can pass parameters to the goal with standard Maven command line properties. For example:

  • mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate

This will run MBG and instruct it to overwrite any existing Java files it may find.

In a continuous build environment, you may want to automatically execute MBG as a part of a Maven build. This can be accomplished by configuring the goal to execute automatically. An example of this is shown below:

   <project ...>
     ...
     <build>
       ...
       <plugins>
        ...
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.4.1</version>
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        ...
      </plugins>
      ...
    </build>
    ...
  </project>

The MBG plugin is bound to the generate-sources phase of a Maven build, so it will execute before the compile step. Also note that MBG generates both Java source files and XML resources. The MBG goal will bind both generated Java files and XML resources to the build and they will both be included in any JAR generated by the build.

MyBatis Generator Configuration Properties

Any property specified in the POM will be passed into the configuration file and may be used in the normal way. For example:

   <project ...>
     ...
     <properties>
       <dao.target.dir>src/main/java</dao.target.dir>
     </properties>
     ...
     <build>
       ...
       <plugins>
        ...
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.4.1</version>
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        ...
      </plugins>
      ...
    </build>
    ...
  </project>

In this case, the property may be accessed in the configuration file with the syntax ${dao.target.dir}.

Classpath Issues

Initially, the plugin classpath is very limited - it only contains MyBatis generator itself. If you need to add something to the plugin’s classpath (for example, a JDBC driver), you can do it by adding dependencies to the plugin configuration like this:

   <project ...>
     ...
     <build>
       ...
       <plugins>
        ...
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.4.1</version>
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
            </execution>
          </executions>
          <dependencies>
            <dependency>
              <groupId>org.hsqldb</groupId>
              <artifactId>hsqldb</artifactId>
              <version>2.3.4</version>
            </dependency>
          </dependencies>
        </plugin>
        ...
      </plugins>
      ...
    </build>
    ...
  </project>

If the dependencies you need are already included as dependencies of the project, then you can also use one of the configuration parameters related to the plugin classpath - “includeCompileDependencies” or “includeAllDependencies” see below for details about those properties.

Parameter Reference

All parameters are optional and most have suitable defaults.

Parameter Expression Type Comments
configurationFile ${mybatis.generator.configurationFile java.io.File The location of the XML configuration file.Default value:${basedir}/src/main/resources/generatorConfig.xml
contexts ${mybatis.generator.contexts java.lang.String A comma delimited list of contexts to use in the current run. Any id specified in the list must exactly match the value of the id attribute of an configuration element. Only ids specified in this list will be active for this run. If this parameter is not specified, then all contexts will be active.
jdbcDriver ${mybatis.generator.jdbcDriver java.lang.String If you specify a sqlScript, then this is the fully qualified JDBC driver class name to use when connecting to the database.
jdbcPassword ${mybatis.generator.jdbcPassword java.lang.String If you specify a sqlScript, then this is the password to use when connecting to the database.
jdbcURL ${mybatis.generator.jdbcURL java.lang.String If you specify a sqlScript, then this is the JDBC URL to use when connecting to the database.
jdbcUserId ${mybatis.generator.jdbcUserId java.lang.String If you specify a sqlScript, then this is the JDBC user ID to use when connecting to the database.
outputDirectory ${mybatis.generator.outputDirectory java.io.File The directory where files generated by MBG will be placed. This directory is used whenever a targetProject in the configuration file is set to the special value “MAVEN” (case sensitive).Default value:${project.build.directory}/generated-sources/mybatis-generator
overwrite ${mybatis.generator.overwrite boolean If true, then existing Java files will be overwritten if an existing Java file if found with the same name as a generated file. If not specified, and a Java file already exists with the same name as a generated file, then MBG will write the newly generated Java file to the proper directory with a unique name (e.g. MyClass.java.1, MyClass.java.2, etc.). **Important: MBG will always merge and overwrite XML files.**Default value:false
sqlScript ${mybatis.generator.sqlScript java.lang.String Location of a SQL script file to run before generating code. If null, then no script will be run. If not null, then jdbcDriver, jdbcURL must be supplied also. In addition, jdbcUserId and jdbcPassword may be supplied if the database requires authentication.Value can be specified as a location in the file system or, if prefixed with “classpath:” a location on the build classpath.
verbose ${mybatis.generator.verbose boolean If true, then MBG will write progress messages to the build log.
includeCompileDependencies ${mybatis.generator.includeCompileDependencies boolean If true, then dependencies with scope “compile”, “provided”, and “system” will be added to the generator’s classpath.
includeAllDependencies ${mybatis.generator.includeAllDependencies boolean If true, then dependencies with any scope will be added to the generator’s classpath.

11

Interpretation of targetProject

The targetProject attribute of the generator configurations is interpreted differently when running with Maven. If set to the special value “MAVEN” (case sensitive), then targetProject will be set to the plugin’s output directory, and that directory will be created if it doesn’t already exist. If not set to “MAVEN”, then targetProject will be interpreted as normal by MBG - it must be set to a directory that already exists.

Tasks After Running MyBatis Generator

After you run MyBatis Generator (MBG), you will need to create or modify other MyBatis configuration artifacts. The main task is to create or modify a MapperConfig.xml file.

Updating the MapperConfig.xml File (MyBatis 3.x)

MyBatis 3.x uses an XML file, commonly named MapperConfig.xml, to specify information for a database connection, a transaction management scheme, and XML mapper files that will be used in a MyBatis session. MBG cannot create this file for you because it knows nothing about your execution environment. However, some of the items in this file relate directly to MBG generated items. Please refer to the standard MyBatis data mapper developer guide for details about the different configuration options.

MBG specific needs in the configuration file are as follows:

  • MBG generated XML mapper files must be listed

For example, suppose that MBG has generated an XML mapper file called MyTableMapper.xml, and that the file has been placed in the test.xml package of your project. The MapperConfig.xml file should have these entries:

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

  <configuration>
    <!-- Setup the transaction manager and data source that are
         appropriate for your environment
    -->
    <environments default"...">
      <environment id"...">
        <transactionManager type="...">
        </transactionManager>
        <dataSource type="...">
        </dataSource>
      </environment>
    </environments>

    <mappers>
      <!-- XML mapper files should be listed here -->
      <mapper resource="test/xml/MyTable_SqlMap.xml" />
    </mappers>

  </configuration>

If there is more than one XML mapper file (as is quite common), then the files can be listed in any order with repeated <mapper> elements after the <mappers> element.

If you use Java based configuration, or Spring, then you will need to register mappers with your configuration in the manner applicable for your environment.

MyBatis GeneratorXML Configuration File Reference

refer to : https://mybatis.org/generator/configreference/xmlconfig.html

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.

MySql Usage Notes

Unsigned Fields

MySql supports both signed, and unsigned, numeric fields. These are not JDBC types, so MyBatis generator cannot automatically account for these types of fields. The Java data types are always signed. This can lead to a loss of precision when using unsigned fields. The solution is to provide a <columnOverride> for any unsigned numeric field in MySql. Here is an example of how to deal with an unsigned bigint field in MySql:

  <table tableName="ALLTYPES" >
    <columnOverride column="UNSIGNED_BIGINT_FIELD" javaType="java.lang.Object" jdbcType="LONG" />
  </table>

You will have to cast the returned value to the appropriate type yourself (in this case, java.math.BigInteger).

Catalogs and Schema

MySql does not properly support SQL catalogs and schema. If you run the create schema command in MySql, it actually creates a database - and the JDBC driver reports it back as a catalog. But MySql syntax does not support the standard catalog..table SQL syntax.

For this reason, it is best to not specify either catalog or schema in generator configurations. Just specify table names and specify the database in the JDBC URL.

If you are using version 8.x of Connector/J you may notice that the generator attempts to generate code for tables in the MySql information schemas (sys, information_schema, performance_schema, etc.) This is probably not what you want! To disable this behavior, add the property “nullCatalogMeansCurrent=true” to your JDBC URL.

For example:

    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/my_schema"
            userId="my_user" password="my_password">
        <property name="nullCatalogMeansCurrent" value="true" />
    </jdbcConnection>

评论