Mybatis----MyBatis Generator (MBG)简介

                            Mybatis----MyBatis Generator (MBG)简介

MyBatis Generator (MBG)简介

MBG生成代码文件

MBG Quick Start Guide

MBG配置文件示例

MBG运行方式

1.From a Command Prompt

2.Running MyBatis Generator With Ant

3.Running MyBatis Generator With Maven

4.Running MyBatis Generator With Java

5.Running MyBatis Generator with Eclipse


MyBatis Generator (MBG)是Mybatis代码生成器,可以用来快速产生对于数据库表的基本增删改查操作。

说明文档地址:http://mybatis.org/generator/

github地址:https://github.com/mybatis/generator

MyBatis Generator (MBG)简介

官方对于MBG的介绍:

MyBatis Generator (MBG) is a code generator for MyBatis MyBatis and iBATIS. It will generate code for all versions of MyBatis, and versions of iBATIS after version 2.2.0. It will introspect a database table (or many tables) and will generate artifacts that can be used to access the table(s). This lessens the initial nuisance of setting up objects and configuration files to interact with database tables. MBG seeks to make a major impact on the large percentage of database operations that are simple CRUD (Create, Retrieve, Update, Delete). You will still need to hand code SQL and objects for join queries, or stored procedures.

MyBatis生成器(MBG)是MyBatis MyBatis和iBATIS的代码生成器。它将为MyBatis的所有版本以及2.2.0版之后的iBATIS版本生成代码。它将内省一个数据库表(或多个表),并生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的最初麻烦。MBG试图对大部分简单CRUD(Create、Retrieve、Update、Delete)的数据库操作产生重大影响。仍然需要手工编写SQL和对象以用于连接查询或存储过程。

MBG生成代码文件

MBG可以生成以下文件:

1.与表结构匹配的Java POJO。

  • a class to match the primary key of the table (if there is a primary key)
  • a class to match the non-primary key fields of the table (except BLOB fields)
  • a class to include the BLOB fields of a table (if the table has BLOB fields)
  • a class to enable dynamic selects, updates, and deletes

 

注意,生成器可以配置为生成不同类型的POJO层次结构-例如,可以选择为每个表生成一个域对象。

2.MyBatis/iBATIS兼容的SQL映射XML文件。

MBG为配置中的每个表上的简单CRUD函数生成SQL。生成的SQL语句包括:

  • insert
  • update by primary key
  • update by example (using a dynamic where clause)
  • delete by primary key
  • delete by example (using a dynamic where clause)
  • select by primary key
  • select by example (using a dynamic where clause)
  • count by example

根据表的结构,这些语句有不同的变体(例如,如果表没有主键,那么MBG将不会生成updatebyprimarykey函数)。

3.适当使用上述对象的Java类。

Java类的生成是可选的。MBG将为MyBatis3.x生成以下类型的Java客户端:

A mapper interface that works with the MyBatis 3.x mapper infrastructure

MBG将为iBATIS 2.x生成以下类型的Java客户端:

  • DAOs that conform to the Spring framework
  • DAOs that only use the iBATIS SQL mapping API. These DAOs can be generated in two varieties: supplying the SqlMapClient through either constructor or setter injection.
  • DAOs that conform to the iBATIS DAO Framework (an optional part of iBATIS, this framework is now deprecated and we suggest that you use the Spring framework instead)

MyBatis生成器设计为在迭代开发环境中运行良好,可以作为Ant任务或Maven插件包含在连续构建环境中。迭代运行MBG时需要注意的重要事项包括:

如果存在与新生成的XML文件同名的现有文件,则MGB将自动合并XML文件。MBG不会覆盖您对它生成的XML文件所做的任何自定义更改。可以反复运行,而不必担心丢失对XML的自定义更改。MBG将替换在上一次运行中生成的任何XML元素。

MGB不会合并Java文件,它可以覆盖现有文件,也可以用不同的唯一名称保存新生成的文件。如果对生成的Java文件进行更改并迭代运行MBG,则必须手动合并更改。当作为Eclipse插件运行时,MBG可以自动合并Java文件。

当反复运行MBG时,XML会自动合并,Java文件不会合并而会替换,可以使用Eclipse插件来实现Java文件的自动合并。

https://marketplace.eclipse.org/content/mybatis-generator

MBG除了JRE之外没有依赖项。需要JRE 6.0或更高版本。此外,还需要一个实现DatabaseMetaData接口的JDBC驱动程序,特别是getColumns和getPrimaryKeys方法。

MBG Quick Start Guide

1.创建并适当地填写配置文件。

必须至少指定:

<jdbcConnection> 指定如何连接到目标数据库元素

<javaClientGenerator>为生成的Java模型对象指定目标包和目标项目

<javaClientGenerator>为生成的Client接口和类指定目标包和目标项目(如果不希望生成,可以省略<javaClientGenerator>元素)

<table>至少一个数据库元素

2.将文件保存在方便的位置(如\temp\generatorConfig.xml)

3.使用以下命令从命令行运行MBG:

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

这将告诉MBG使用您的配置文件运行。它还将告诉MGB改写具有相同名称的任何现有Java文件。如果您想保存任何现有的Java文件,那么省略-重写参数。如果有冲突,MBG将用一个唯一的名称(例如MyClass.java.1)保存新生成的文件。

4.在运行MBG之后,需要创建或修改标准的MyBatis或iBATIS配置文件,以使用新生成的代码。

有关详细信息,请参阅运行MyBatis生成器后的任务页。

http://mybatis.org/generator/afterRunning.html

MBG配置文件示例

在最常见的用例中,MyBatis生成器(MBG)由XML配置文件驱动。配置文件告诉MBG:

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

配置文件实例如下:

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

配置文件详细说明;http://mybatis.org/generator/configreference/xmlconfig.html

MBG运行方式

MBG可以以以下方式来启动

1.From a Command Prompt

MyBatis生成器(MBG)可以直接从命令提示符运行。JAR清单包含默认类(org.mybatis.generator.api.ShellRunner)的名称,或者您可以自己指定它。必须创建XML配置文件才能从命令行运行MBG。如果文件名为“generatorConfig.xml”,则以下任何命令行都将运行MBG:

   java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml
   java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite
   java -cp mybatis-generator-core-x.x.x.jar org.mybatis.generator.api.ShellRunner -configfile generatorConfig.xml
   java -cp mybatis-generator-core-x.x.x.jar org.mybatis.generator.api.ShellRunner -configfile generatorConfig.xml -overwrite

ShellRunner类接受多个参数,具体如下:

ArgumentValue
-configfile file_name
(required)
Specifies the name of the configuration file.
-overwrite (optional)If specified, 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: The generator will always merge and overwrite XML files.
-verbose (optional)If specified, then progress messages will be written to the console.
-forceJavaLogging (optional)If specified, then MBG will use Java logging rather than Log4J even if Log4J is in the runtime classpath.
-contextids context1,context2,...
(optional)
If specified, then this is 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 <context> configuration element. Only ids specified in this list will be active for this run. If this argument is not specified, then all contexts will be active.
-tables table1, table2,...
(optional)
If specified, then this is a comma delimited list of tables to use in the current run. Any table specified in the list must exactly match the fully qualified table name specified in a <table> configuration element. Only tables specified in this list will be active for this run. If this argument is not specified, then all tables will be active. Specify table names as:

table
schema.table
catalog..table
etc.

2.Running MyBatis Generator With Ant

MyBatis生成器(MBG)包含一个简单的Ant任务。该任务必须在build.xml文件中定义,并且该任务接受多个参数。下面是build.xml文件的示例:

<project default="genfiles" basedir=".">
     <property name="generated.source.dir" value="${basedir}" />

     <target name="genfiles" description="Generate the files">
       <taskdef name="mbgenerator"
                classname="org.mybatis.generator.ant.GeneratorAntTask"
                classpath="mybatis-generator-core-x.x.x.jar" />
       <mbgenerator overwrite="true" configfile="generatorConfig.xml" verbose="false" >
         <propertyset>
           <propertyref name="generated.source.dir"/>
         </propertyset>
       </mbgenerator>
     </target>
   </project>

task属性如下:

AttributeValue
configfile (required)Specifies the name of the configuration file.
overwrite (optional)If "true", "yes", etc., then MBG will overwrite existing Java files if an existing Java file if found with the same name as a generated file. If "false", "no", etc., 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.
contextids (optional)If specified, then this is 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 <context> configuration element. Only ids specified in this list will be active for this run. If this argument is not specified, then all contexts will be active.
tables (optional)If specified, then this is a comma delimited list of tables to use in the current run. Any table specified in the list must exactly match the fully qualified table name specified in a <table> configuration element. Only tables specified in this list will be active for this run. If this argument is not specified, then all tables will be active. Specify table names as:

table
schema.table
catalog..table
etc.
verbose (optional)If "true", "yes", etc., then MBG will log progress messages to the ant console (if Ant is running in verbose mode). The default is "false".

<taskdef>上的类路径用于告诉Ant MBG JAR文件的位置。如果使用Ant手册中描述的其他方法之一将MBG添加到Ant类路径,则这是可选的;

任务的名称可以是您想要的任何东西,“mbgenerator”只是一个例子;

该任务支持可选的嵌套<property set>元素,该元素是标准的Ant属性集类型。这可用于将参数传递到配置文件中。例如,可以在配置文件中使用转义序列${generated.source.dir}访问上述属性generated.source.dir;

如果在配置文件中指定了属性但未解析,则转义的属性字符串将按“原样”传递到生成的代码中。

3.Running MyBatis Generator With Maven

在日常开发中主要使用该种方式,MyBatis生成器(MBG)包含一个Maven插件,用于集成到Maven构建中。为了与Maven的按约定配置策略保持一致,在Maven构建中包含MBG可能非常简单。最低配置如下所示:

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

Maven执行目标如下:

mybatis-generator:generate

该目标并不会自动执行,可以通过两种方式来执行:

通过命令行或者传递参数给maven plugin

mvn mybatis-generator:generate

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

在连续构建环境中,如果希望作为Maven构建的一部分自动执行MBG。这可以通过将目标配置为自动执行来实现。示例如下所示:

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

MBG插件绑定到Maven构建的generate sources阶段,因此它将在编译步骤之前执行。还要注意,MBG同时生成Java源文件和XML资源。MBG目标将生成的Java文件和XML资源绑定到构建,并且它们都将包含在构建生成的任何JAR中。

MyBatis生成器配置属性

在pom文件中配置属性会传递到配置文件中,例如

<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.3.7</version>
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        ...
      </plugins>
      ...
    </build>
    ...
  </project>

可以在配置文件中使用${dao.target.dir}来使用上述定义的属性。

最初,插件类路径非常有限-它只包含MyBatis生成器本身。如果需要向插件的类路径(例如,JDBC驱动程序)添加一些内容,可以通过向插件配置添加依赖项来完成,如下所示:

<project ...>
     ...
     <build>
       ...
       <plugins>
        ...
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.7</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>

可以配置参数如下

ParameterExpressionTypeComments
configurationFile${mybatis.generator.configurationFile}java.io.FileThe location of the XML configuration file.

Default value:

${basedir}/src/main/resources/generatorConfig.xml
contexts${mybatis.generator.contexts}java.lang.StringA 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 <context> 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.StringIf 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.StringIf you specify a sqlScript, then this is the password to use when connecting to the database.
jdbcURL${mybatis.generator.jdbcURL}java.lang.StringIf you specify a sqlScript, then this is the JDBC URL to use when connecting to the database.
jdbcUserId${mybatis.generator.jdbcUserId}java.lang.StringIf you specify a sqlScript, then this is the JDBC user ID to use when connecting to the database.
outputDirectory${mybatis.generator.outputDirectory}java.io.FileThe 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}booleanIf 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.StringLocation 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.

tableNames${mybatis.generator.tableNames}java.lang.StringIf specified, then this is a comma delimited list of tables to use in the current run. Any table specified in the list must exactly match the fully qualified table name specified in a <table> configuration element. Only tables specified in this list will be active for this run. If this argument is not specified, then all tables will be active. Specify table names as:

table
schema.table
catalog..table
etc.

verbose${mybatis.generator.verbose}booleanIf true, then MBG will write progress messages to the build log.
includeCompileDependencies${mybatis.generator.includeCompileDependencies}booleanIf true, then dependencies with scope "compile", "provided", and "system" will be added to the generator's classpath.
includeAllDependencies${mybatis.generator.includeAllDependencies}booleanIf true, then dependencies with any scope will be added to the generator's classpath.

与Maven一起运行时,生成器配置的targetProject属性的解释不同。如果设置为特殊值“Maven”(区分大小写),那么targetProject 项目将被设置为插件的输出目录,如果该目录不存在,则该目录将被创建。如果没有设置为“Maven”,那么目标项目将被MPG解释为正常-必须将其设置为已经存在的目录。

4.Running MyBatis Generator With Java

MyBatis生成器(MBG)可以直接从Java调用。对于配置,可以使用XML配置文件,也可以使用Java完全配置MBG。

下面的代码示例演示如何使用基于XML的配置从Java调用MBG。它不显示异常处理,但从编译器错误中可以明显看出:)

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

配置文件属性可以作为配置分析器构造函数上的参数传递给分析器。如果未显式传递,则将搜索JVM系统属性以查找配置文件属性的值。例如,可以在配置文件中使用转义序列${generated.source.dir}访问属性generated.source.dir。如果在配置文件中指定了属性但未解析,则转义的属性字符串将按“原样”传递到生成的代码中。

下面的代码示例演示如何使用基于Java的配置从Java调用MBG

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

5.Running MyBatis Generator with Eclipse

安装Eclipse Feature

  • Search for "MyBatis Generator" in the Eclipse marketplace and install directly from the marketplace. You can access the eclipse marketplace in two ways:
    1. Take the menu option Help>Eclipse Marketplace... in a running eclipse instance
    2. Go to https://marketplace.eclipse.org/
  • Manually configure an update site that points to https://dl.bintray.com/mybatis/mybatis-generator
  • Download the zipped eclipse update site from the GitHub release page (https://github.com/mybatis/generator/releases), unzip, and configure an update site that points to your unzipped directory.

安装MBG插件之后,编写配置文件,运行MBG即可。

To get up and running quickly with MyBatis Generator in the eclipse environment, follow these steps:

  1. Create a configuration file:
    1. File>New>Other...
    2. Select "MyBatis Generator Configuration File" from the "MyBatis" category, then press "Next"
    3. Specify the location of the file, and the name of the file (defaults to generatorConfig.xml)
    4. Finish the wizard
  2. Fill out the configuration file appropriately. At a minimum, you must specify:
    1. jdbcConnection information to specify how to connect to the target database
    2. A target package, and target project for the javaModelGenerator
    3. A target package, and target project for the sqlMapGenerator
    4. A target package, target project, and type for the javaClientGenerator (or you can remove the javaClientGenerator element if you don't wish to generate Java Clients)
    5. At least one database table
  3. Save the file
  4. Right click on the configuration file in Eclipse's navigator, or package explorer, view and take the menu option "Run As>Run MyBatis Generator"
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis GeneratorMBG)是一个代码生成器,用于为MyBatis和iBATIS生成代码。它可以根据数据库表结构自动生成访问表的代码。MBG的主要目的是简化与数据库表交互的初始设置,并减少常见的CRUD(创建,检索,更新,删除)操作的代码编写工作。然而,MBG仅生成简单的CRUD操作,对于连接查询或存储过程等复杂操作,仍然需要手动编写SQL和对象代码。 MBG可以生成多种类型的Java客户端类,适用于MyBatis 3.x的映射器接口。这些Java客户端类可以用于与数据库表进行交互。 要使用MyBatis Generator,您需要在项目的pom.xml文件中引入相应的依赖。在plugin标签中配置mybatis-generator-maven-plugin插件,并指定生成配置文件的路径、是否覆盖已有文件以及是否显示详细输出信息。 您可以在pom.xml中的dependencies标签中引入mysql-connector-java依赖,以便在生成代码时与MySQL数据库进行交互。 总结起来,MyBatis Generator是一个用于生成MyBatis和iBATIS代码的工具,可以根据数据库表结构自动生成访问表的代码。它可以生成简单的CRUD操作的代码,并且可以生成适用于MyBatis 3.x的Java客户端类。要使用MyBatis Generator,您需要在项目的pom.xml文件中配置相应的插件和依赖。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [MyBatis Generator使用方法(详细)](https://blog.csdn.net/qq_48581332/article/details/123674440)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值