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

Mybatis Generator学习

时间:2021-06-07 20:05:20      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sed   primary   connect   chm   sele   cat   相关   有用   result   

1.作用

  它可以根据数据库中的表,来帮我们生成供mybatis使用使用实体类,xml和接口类。

2.基本用法

  在maven的pom文件中引入MBG(MyBatis Generator)jar包

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>

  配置generatorConfig.xml文件,到时候就是根据这个文件来生成实体类,(增删改查)接口,sql.xml文件。

<?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>
    <!-- 指定MBG运行生成对象的环境信息,targetRuntime是枚举值,看官网按需选择 -->
    <context id="grate" targetRuntime="MyBatis3">
        <!-- 去除所有注释,默认的注释没什么用,很冗余,这里是我自己重写了一下默认的接口,就保留一个字段的注释,暂时可以把这个去掉看效果 -->
        <commentGenerator type="com.cls.all.great.mbg.comment.MyCommentGenerator">
           <!-- <property name="addRemarkComments" value="true" />-->
        </commentGenerator>
        <!--数据连接信息-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/dbName"
                        userId="111"
                        password="222">
        </jdbcConnection>

        <!--java实体类的目标路径等,根据实际编写,targetProject的路径必须是已经存在的-->
        <javaModelGenerator targetPackage="pojo" targetProject="\codeSpace\MGB">
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- 生成SQL.xml的目标路径-->
        <sqlMapGenerator targetPackage="mapper"  targetProject="\codeSpace\MGB">
        </sqlMapGenerator>

        <!-- 用来控制生成java接口类,可选配置,不指定该元素时,不会生成java客户端接口(就是那个接口) -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="mapper"  targetProject="\codeSpace\MGB">
        </javaClientGenerator>

     <!-- 配置数据库表的,catalog是你的数据库名字,oracle用schema --> <table catalog="grate" tableName="users" enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" enableSelectByPrimaryKey="true" selectByPrimaryKeyQueryId="false" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>

上面是一个基本的配置,还有很多的属性可以配置,如果只是看一下MBG的效果,已经ok。详细的可以看官网介绍,按需添加自己的配置。最下面是我觉得重要的几个属性官网翻译(个人加有道翻译)。

 

然后运行一下,我这里使用java代码运行的(也可以直接用maven插件跑):

package com.cls.all.great.mbg;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MbgGenerator {

    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("generatorConfig.xml");
        System.out.println(configFile.getAbsolutePath());
        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);
        System.out.println(warnings.toString()); // 要是不成功,可以把错误打印出来,看错误
    }
}

效果,

技术图片

 

 

 技术图片

 

 

 

个人翻译的几个官网几个要素:

The <table> Element

The <table> element is used to select a table in the database for introspection. Selected tables will cause the following objects to be generated for each table:

该元素是用来选择你数据库中的表。你选择的表将会生成一下几个对象:

  • A MyBatis formatted SQL Map file
  • 一份mybatis的sql map文件
  • A set of classes that form the "model" of the table including:(一个model类,它包含:)
    • A class to match the primary key of the table (if the table has a primary key).
    • A class to match the fields in the table that are not in the primary key, and non BLOB fields. This class will extend the primary key if there is one.
    • A class to hold any BLOB fields in the table, if there are any. This class will extend one of the two previous classes depending on the configuration of the table.
    • A class that is used to generate dynamic where clauses in the different "by example" methods (selectByExample, deleteByExample).
  • (Optionally) A MyBatis mapper interface(一个map接口(可选))

At least one <table> element must be specified as a required child element of the <context> element. You can specify unlimited table elements.

在<context>元素下,你必须配置至少一个<table>元素。你可以配置无限多的table元素

Database Identifiers (数据库定义)

MyBatis Generator (MBG) tries to deal with the case sensitivity of database identifiers automatically. In most cases, MBG is able to find tables regardless of what you specify for catalog, schema, and tableName attributes. MBG‘s process follows these steps:

MBG会自动处理数据库的相关信息。在大多数场景下,尽管你没有指定目录,表空间和表名称,MBG也能够扫描到表。MBG的处理流程是这样的:

  1. If either of the catalog, schema, or tableName attributes contain a space, then MBG will look for tables based on the exact case specified. In this case, MBG will automatically delimit the table identifiers in the generated SQL.
  2. Else if the database reports that identifiers are stored in upper case, MBG will automatically convert any table identifier to upper case.
  3. Else if the database reports that identifiers are stored in lower case, MBG will automatically convert any table identifier to lower case.
  4. Else MBG will look for tables based on the exact case specified.

In most cases, this process works perfectly. However, there are cases where it will fail. For example, suppose you create a table like this:

在大多数场景中,该过程可以正确的执行。然而,有时候会失败。例如,你可能会创建出一个如下的类:

  create table "myTable" (
     ...some columns
  )

Because the table name is delimited, most databases will create the table with the exact case specified - even if the database normally stores identifiers in upper case. In this instance, you should specify the attribute delimitIdentifiers="true" in the table configuration.

因为表名被分隔符分割了,在大多数数据库中使用指定的大小写来创建表,即使数据库通常以大写形式存储标识符也是如此。这这种情况下,你应该指定“delimitIdentifiers”为true。

Required Attributes

AttributeDescription
tableName The name of the database table (not including the schema or catalog). The specified value can contain SQL wildcards if so desired.

Optional Attributes

AttributeDescription
schema(表空间-oracle) The database schema - not required if your database does not use schemas, or if there is a default schema. The specified value can contain SQL wildcards if so desired.
catalog(目录-mysql) The database catalog - not required if your database does not use catalogs, or if there is a default catalog.
alias(别名)

This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
If specified, this value will be used to alias the table and all column names in any generated SQL select statement. Column names will be aliased with the pattern alias_actualColumnName.

该属性在 "MyBatis3DynamicSql" 和"MyBatis3Kotlin"中,会被忽略。

如果指定,该值将会作用在该表和该表的所有字段中(sqlMapper.xml中也是)。

domainObjectName

The base name from which generated object names will be generated. If not specified, MBG will generate a name automatically based on the tableName. The name (either specified here, or generated automatically) will be used to compute generated domain class names and DAO class names.

生成对象的名字。如果不指定,MBG会自动使用表名作为对象名。

You can specify a package fragment in the domain object name. For example, if you specify foo.Bar then the domain object will be Bar and package foo will be appended to the target package specified in the generator configurations.

同时,你也可以使用 包名+类名的方式。如: foo.bar。生成的对象类名为bar,在foo包下。

mapperName

The name of the MyBatis3 generated mapper class and XML file. If not specified, the name will be whatever the domain object name is, plus the word "Mapper".

指定mapper接口和xml的名字。如果不指定,默认的名字就是“表名+Mapper”

You can specify a package fragment in the mapper name. For example, if you specify foo.BarMapper then the mapper will be BarMapper and package foo will be appended to the target package specified in the generator configurations.

Since version 1.3.4

sqlProviderName This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
The name of the MyBatis3 generated SQL provider class (which may or may not be generated based on the configuration). If not specified, the name will be whatever the domain object name is, plus the word "SqlProvider".

You can specify a package fragment in the SQL provider name. For example, if you specify foo.BarSqlProvider then the SQL provider will be BarSqlProvider and package foo will be appended to the target package specified in the generator configurations.

Since version 1.3.4

enableInsert This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether an insert statement should be generated.

The default is true.

enableSelectByPrimaryKey This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether a select by primary key statement should be generated. Regardless of this setting, the statement will not be generated if the table does not have a primary key.

The default is true.

enableSelectByExample This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether a select by example statement should be generated. This statement enables many different dynamic queries to be generated at run time.

The default is true.

enableUpdateByPrimaryKey This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether an update by primary key statement should be generated. Regardless of this setting, the statement will not be generated if the table does not have a primary key.

The default is true.

enableDeleteByPrimaryKey This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether an delete by primary key statement should be generated. Regardless of this setting, the statement will not be generated if the table does not have a primary key.

The default is true.

enableDeleteByExample This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether a delete by example statement should be generated. This statement enables many different dynamic deletes to be generated at run time.

The default is true.

enableCountByExample This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether a count by example statement should be generated. This statement will return the number of rows in a table that match an example.

The default is true.

enableUpdateByExample This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
Signifies whether an update by example statement should be generated. This statement will update rows in a table that match an example. If true, an update by example "selective" statement will also be generated. The "selective" statement will only update columns where the corresponding value in the record parameter is non-null.

The default is true.

selectByPrimaryKeyQueryId This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
This value will be added to the select list of the select by primary key statement in this form: "‘<value>‘ as QUERYID". This can be useful for identifying queries in DBA tracing tools at run time. If you use thus value, you should specify a unique id for every different query generated by MBG.
selectByExampleQueryId This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
This value will be added to the select list of the select by example statement in this form: "‘<value>‘ as QUERYID". This can be useful for identifying queries in DBA tracing tools at run time. If you use thus value, you should specify a unique id for every different query generated by MBG.
modelType This attribute is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
This attribute is used to override the default model type if you desire to do so for this table. If not specified, MBG will generate domain objects based on the context default model type. The model type defines how MBG will generate domain classes. With some model types MBG will generate a single domain class for each table, with others MBG may generate different classes depending on the structure of the table. The property supports these values:
conditional This model is similar to the hierarchical model except that a separate class will not be generated if that separate class would only contain one field. So if a table has only one primary key field, that field will be merged into the base record class.
flat This model generates only one domain class for any table. The class will hold all fields in the table.
hierarchical This model will generate a primary key class if the table has a primary key, another class that holds any BLOB columns in the table, and another class that holds the remaining fields. There is an appropriate inheritance relationship between the classes.
escapeWildcards Signifies whether SQL wildcards (‘_‘ and ‘%‘) in the schema and tableName should be escaped when searching for columns. This is required by some drivers if the schema or tableName includes an SQL wildcard (for example, if a table name is MY_TABLE, some drivers require that the underscore character be escaped).

The default is false.

delimitIdentifiers Signifies whether MBG should use the exact case specified when searching for tables and then delimit the identifiers in the generated SQL. See the discussion above for more details.

The delimiter characters are specified on the <context> element.

The default is false unless the catalog, schema, or tableName attributes contain a space, then true.

delimitAllColumns Signifies whether MBG should add delimiters to all column names in the generated SQL. This is an alternative to coding a <columnOverride> for every column specifying that the column should be delimited. This is useful for databases like PostgreSQL that are case sensitive with identifiers.

The delimiter characters are specified on the <context> element.

The default is false.

Child Elements

Supported Properties

This table lists the properties of the default SQL Map generators that can be specified with the <property> child element:

Property NameProperty Values
constructorBased This property is ignored is the target runtime is "MyBatis3Kotlin"
This property is used to select whether MyBatis Generator will generate a constructor for the class that accepts a value for each field in the class. Also, the SQL result map will be built to use the constructor rather than the "setter" for each field.

This property is ignored (and forced "true") if the "immutable" property is set "true".

The default value is false.

ignoreQualifiersAtRuntime If true, then MBG will not add the schema or catalog to the table name in the generated SQL. This is useful if you have tables with the same name in several schemas - you can use MBG to generate objects based on the table in one schema, but not include the schema for runtime.

 

The default value is false.

immutable This property is ignored is the target runtime is "MyBatis3Kotlin"
This property is used to select whether MBG will generate immutable model classes - this means that the classes will not have "setter" methods and the constructor will accept values for each field in the class.

If true, this forces the model classes to be built with paramterized constructors regardless of the value of the "constructorBased" property.

The default value is false.

modelOnly This property is used to select whether MBG will only generate model classes for a table.

If true, then a Java client will not be generated. If an <sqlMapGenerator> is configured and this property is set true then MBG will only generate result map elements in the SQL Mapper XML file for this table.

If true, then this value overrides any of the "enable*" attributes on the <table> element - no CRUD methods will be generated.

The default value is false.

rootClass This attribute is ignored is the target runtime is "MyBatis3Kotlin"
This property can be used to specify a root class for all generated Java model objects. MBG will specify this value as the super class of the primary key object, if the table has a primary key, or the record object otherwise. The value specified in this property will override the rootClass property set on the Java Model Generator configuration if any is set.

Important: If MBG is able to load the root class, it will not override a property in the root class that exactly matches a property that would normally be generated. An exact match of a property is defined as follows

  • Property name matches exactly
  • Property is of the same type
  • Property has a "getter" method
  • Property has a "setter" method

If specified, the value of this property should be a fully qualified class name (like com.mycompany.MyRootClass).

rootInterface This property is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
This property can be used to specify a super interface for all generated DAO interface objects. The value specified in this property will override the rootInterface property set on the DAO Generator configuration if any is set.

Important: MBG does not verify that the interface exists, or is a valid Java interface.

If specified, the value of this property should be a fully qualified interface name (like com.mycompany.MyRootInterface).

runtimeCatalog If you specify a value for this property, than MBG will use that value as the catalog in the generated SQL rather than the catalog as configured above. This is useful if you want to generate code against one catalog, but want to use a different catalog at runtime.
runtimeSchema If you specify a value for this property, than MBG will use that value as the schema in the generated SQL rather than the schema as configured above. This is useful if you want to generate code against one schema, but want to use a different schema at runtime.
runtimeTableName If you specify a value for this property, than MBG will use that value as the table name in the generated SQL rather than the tableName as configured above. This is especially useful on Oracle if you want to generate objects to use a public synonym. In that case, you will need to generate the objects against the actual table that the synonym points to, then specify the synonym name in this property. You should also specify the ignoreQualifiersAtRuntime property in most cases with public synonyms.
selectAllOrderByClause This property can be used to specify an order by clause that will be added to the selectAll method. This is only applicable if you are using the MyBatis3Simple target runtime. MBG will prepend order by to anything you specify in this property, so the property should contain a column list only (e.g ID1, ID2 or ID1 desc, ID2 asc)
trimStrings This attribute is ignored is the target runtime is "MyBatis3Kotlin"

This property is used to select whether MyBatis Generator adds code to trim the white space from character fields returned from the database. This can be useful if your database stores data in CHAR fields rather than VARCHAR fields. When true, MyBatis Generator will insert code to trim character fields. Can be overridden with the trimStrings property in a <columnOverride> configuration. This property value overrides the property if specified at the <javaModelGenerator> level and can be overridden for fields/columns using the property in a <columnOverride> element.

The default value is inherited from the <javaModelGenerator>, otherwise false.

useActualColumnNames If true, then MBG will use column names as returned from the database metadata as the properties of the generated domain objects. If false (default), MBG will attempt to camel case the returned names. In either event, the name can be specified explicitly by the <columnOverride> element in which case this property will be ignored for the specified column.

For example, suppose a table contains a column START_DATE. If the value of this property is "true", then MBG will generate the property name as START_DATE - meaning that the getters and setters for the value will be getSTART_DATE() and setSTART_DATE(). If the value of this property is false, then MBG will generate the property name as startDate - meaning that the getters and setters for the value will be getStartDate() and setStartDate().

The default value is false.

useColumnIndexes This property is ignored is the target runtime is "MyBatis3DynamicSql" or "MyBatis3Kotlin"
If true, then MBG will generate resultMaps that use column index rather than column name in the result mappings. This is useful when a table has column names differentiated only by the case of the name (e.g. "first name" and "First Name"). There is a slight performance benefit with this support also.

 

The default value is false.

Important Note: This property is not supported if the target runtime is for MyBatis version 3.

useCompoundPropertyNames If true, then MBG will use generate property names by contatenating the column name with the column reparks. This can be usefull in databases created by 4th generation languages where the column names are generated (e.g. FLD2237), but the remarks contain useful information (e.g. "customer id"). In this case, MBG will generate a property name of FLD2237_CustomerId.

The default value is false.

Example

This element specifies that we always want to generate code for a table called MYTABLE in schema MYSCHEMA. We also want to ignore a column called "fred" in the table, and we want to override the column "BEG_DATE" so that the generated property name will be "startDate".

<table tableName="MYTABLE" schema="MYSCHEMA">
  <ignoreColumn column="fred"/>
  <columnOverride column="BEG_DATE" property="startDate"/>
</table>

 

 

 

The <javaModelGenerator> Element

The <javaModelGenerator> element is used to define properties of the Java model generator. The Java Model Generator builds primary key classes, record classes, and Query by Example classes that match the introspected table. This element is a required child element of the <context> element.

该元素是用来定义model生成器的属性的。它用来生成指定表的实体类,记录类和查询类。它是<context>下的一个必要子元素。

Required Attributes

AttributeDescription
targetPackage

This is the package where the generated classes will be placed. In the default generator, the property "enableSubPackages" controls how the actual package is calculated. If true, then the calculated package will be the targetPackage plus sub packages for the table‘s catalog and schema if they exist. If false (the default) then the calculated package will be exactly what is specified in the targetPackage attribute. MyBatis Generator will create folders as required for the generated packages.

这个是生成类放置的地方(package)。默认的生成器,“enableSubPackages”属性控制真正的package。如果是true,targetPackage会被放置在表目录(如果存在)下面。如果是false(默认),指定的package就是真正的存放路径。MBG将会创建文件夹为目标package。

targetProject

This is used to specify a target project for the generated objects. When running in the Eclipse environment, this specifies the project and source folder where the objects will be saved. In other environments, this value should be an existing directory on the local file system. MyBatis Generator will not create this directory if it does not exist.

这个属性是用来为生成的接口和类,指定一个目标功能。让运行在Eclipse环境下,这个指定project和source文件夹下,对象将会被保存。在其他环境中,该属性指定的值,应该是一个已经存在的文件夹,MBG不会创建该目录,如果文件夹不存在。

Optional Attributes

None

Child Elements

Supported Properties

This table lists the properties of the default Java model generators that can be specified with the <property> child element:

Property NameProperty Values
constructorBased

This property is used to select whether MyBatis Generator will generate a constructor for the class that accepts a value for each field in the class. Also, the SQL result map will be built to use the constructor rather than the "setter" for each field.

该属性用来选择,MBG是否该类生成一个的默认构造器(列举了每个字段)。同样的,sql map也会被使用该构造器来创建,而不是使用setter方法。

This property is ignored (and forced "true") if the "immutable" property is set "true".

如果<immutable>设置成了true,name该属性会被忽略。

This property can be overridden by the corresponding property in a <table> element.

The default value is false.

默认值是false

This property is ignored if the target runtime is "MyBatis3Kotlin"

targetRuntime设置为MyBatis3Kotlin时,该属性无效

enableSubPackages

This property is used to select whether MyBatis Generator will generate different Java packages for the objects based on the catalog and schema of the introspected table.

该属性用来选择MBG生成的类,是基于目录还是表空间来放置。

For example, suppose a table MYTABLE in schema MYSCHMA. Also suppose that the targetPackage attribute is set to "com.mycompany". If this property is true, the generated objects for the table will be placed in the package "com.mycompany.myschema". If the property is false, the generated objects will be placed in the "com.mycompany" schema.

例如,假设一个表MYTABLE在MYCHMA表空间下。同样的,假设targetPackage设置的值是“com.mycompany”。该属性为true,name生成的DAO接口、类会被放在“com.mycompany.myschema”下。如果该属性为false,生成的文件将会被放置在“com.mycompany”下。

The default value is false.

exampleTargetPackage This property is used to specify a different package for the generated example objects. If not specified, the example objects will be generated in the same package as other model objects.

Note: this property is ignored in the MyBatis Dynamic SQL based runtimes.

exampleTargetProject This property is used to specify a different project for the generated example objects. If not specified, the example objects will be generated in the same project as other model objects.

Note: this property is ignored in the MyBatis Dynamic SQL based runtimes.

immutable

This property is used to select whether MyBatis Generator will generate immutable model classes - this means that the classes will not have "setter" methods and the constructor will accept values for each field in the class.

该属性用来选择MBG是否生成不可变的model类。意思就是,生成的model类,没有任何的setter方法和构造函数来接受外部参数。

If true, this forces the model classes to be built with parameterized constructors regardless of the value of the "constructorBased" property.

This property can be overridden by the corresponding property in a <table> element.

The default value is false.

This property is ignored if the target runtime is "MyBatis3Kotlin"

rootClass

This property can be used to specify a root class for all generated Java model objects. MyBatis Generator will specify this value as the super class of the primary key object, if the table has a primary key, or the record object otherwise. This value may be overridden by specifying the rootClass property on a Table configuration.

该属性可以为每个model类指定一个父类。

Important: If MyBatis Generator is able to load the root class, then it will not override a property in the root class that exactly matches a property that would normally be generated. An exact match of a property is defined as follows

不会覆盖父类的成员属性

  • Property name matches exactly
  • Property is of the same type
  • Property has a "getter" method
  • Property has a "setter" method

If specified, the value of this property should be a fully qualified class name (like com.mycompany.MyRootClass).

This property is ignored if the target runtime is "MyBatis3Kotlin"

trimStrings

This property is used to select whether MyBatis Generator adds code to trim the white space from character fields returned from the database. This can be useful if your database stores data in CHAR fields rather than VARCHAR fields. When true, MyBatis Generator will insert code to trim character fields. Can be overridden with the trimStrings property in a <table> or <columnOverride> element.

该属性用来选择,MBG是否为字段增加trim方法来为character字段去除空格。当你的字段在数据库中是char类型而不是varchar类型时,该属性很有用。

The default value is false.

默认是false

This property is ignored if the target runtime is "MyBatis3Kotlin"

Example

This element specifies that we always want to place generated classes in the "‘test.model" package and that we want to use subpackages based on the table schema and catalog. We also want String columns trimmed.

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

 

The <sqlMapGenerator> Element

The <sqlMapGenerator> element is used to define properties of the SQL map generator. The SQL Map Generator builds a MyBatis formatted SQL map XML file for each introspected table.

这个元素是用来定义sql map生成器(xml)的属性的。它为指定的每张表生成mybatis的sql map xml文件。

This element is a required child element of the <context> element only if your chosen javaClientGenerator requires XML. The runtimes based on MyBatis Dynamic SQL do not generate XML and will ignore this element if it is specified.

只有当你选择了<javaClientGenerator>元素时,该元素时必须的。

If you do not specify a javaClientGenerator, then the following rules apply:

如果你没有指定一个<javaClientGenerator>,MBG会遵循以下规则:

  • If you specify an sqlMapGenerator, then MBG will generate SQL map XML files and model classes only.
  • 如果你指定了一个<sqlMapGenerator>,那么MBG仅仅会生成sql.xml文件和model类。
  • If you do not specify an sqlMapGenerator, then MBG will generate model classes only.
  • 如果你没有指定该元素,那么MBG仅仅只会生成model类

Required Attributes(必须元素)

AttributeDescription
targetPackage This is the package where the generated SQL Maps will be placed. In the default generators, the property "enableSubPackages" controls how the actual package is calculated. If true, then the calculated package will be the targetPackage plus sub packages for the table‘s catalog and schema if they exist. If false (the default) then the calculated package will be exactly what is specified in the targetPackage attribute. MyBatis Generator (MBG) will create folders as required for the generated packages.(后面有翻译了)
targetProject This is used to specify a target project for the generated SQL maps. When running in the Eclipse environment, this specifies the project and source folder where the objects will be saved. In other environments, this value should be an existing directory on the local file system. MBG will not create this directory if it does not exist.(后面有翻译了)

Optional Attributes

None

Child Elements

Supported Properties

This table lists the properties of the default SQL Map generators that can be specified with the <property> child element:

Property NameProperty Values

enableSubPackages

(后面有翻译了)

This property is used to select whether MBG will generate different Java packages for the objects based on the catalog and schema of the introspected table.

For example, suppose a table MYTABLE in schema MYSCHMA. Also suppose that the targetPackage attribute is set to "com.mycompany". If this property is true, the generated SQL Map for the table will be placed in the package "com.mycompany.myschema". If the property is false, the generated SQL Map will be placed in the "com.mycompany" schema.

The default value is false.

Example

This element specifies that we always want to place generated SQL Maps in the "‘test.model" package and that we want to use subpackages based on the table schema and catalog.

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

 

The <javaClientGenerator> Element

The <javaClientGenerator> element is used to define properties of the Java client generator. The Java client Generator builds Java interfaces and classes that allow easy use of the generated Java model and XML map files. For MyBatis, the generated objects take the form of mapper interfaces. This element is a optional child element of the <context> element. If you do not specify this element, then MyBatis Generator (MBG) will not generate Java client interfaces and classes.

<javaClientGenerator>元素被用来定义java client生成器的属性。java client生成器生成java接口类,它(接口)可以用来简单的使用生成的java model类和xml文件。对于mybatis,是采用mapper接口方式来生成对象的。该元素是<context>下的一个可选元素。如果你不指定该元素,MBG将不会生成java client接口类。

Required Attributes(必须元素)

AttributeDescription
type

This attribute is used to select one of the predefined Java Client generators, or to specify a user provided Java Client generator. Any user provided generator must extend the class org.mybatis.generator.codegen.AbstractJavaClientGenerator class, and must have a public default constructor.

该元素被用来指定一个预先预定好的java client生成器,或者指定一个用户提供的java client生成器。该生成器必须继承org.mybatis.generator.codegen.AbstractJavaClientGenerator类,还有必须要有一个默认的public构造器。

The attribute accepts the following values for selecting one of the predefined generators:

If the <context> targetRuntime is MyBatis3DynamicSql this attribute is optional and ignored.

If the <context> targetRuntime is MyBatis3Kotlin this attribute is optional and ignored.
If the <context> targetRuntime is MyBatis3 the following predefined values can be used:
ANNOTATEDMAPPER

The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on annotations and MyBatis 3.x SqlProviders. No XML mapper files will be generated.

生成的对象是满足MyBatis 3.x版本的接口。这些接口是基于注解和MyBatis 3.x版本的。没有xml文件会被生成。

The ANNOTATEDMAPPER requires MyBatis version 3.0.4 or higher.(版本要求)

MIXEDMAPPER

The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on a mix of annotations and XML. An annotation will be used where a simple annotation will work. This client will not generate and Sql Provider, so all complex dynamic SQL will be generated in XML.

生成的对象是满足MyBatis 3.x版本的接口。这些接口是基于注解和xml混合模式的。只会简单生成的注解,client不会提供sql。所以复杂的动态sql将会被生成到xml中。

The MIXEDMAPPER requires MyBatis version 3.0.4 or higher.(版本要求)

XMLMAPPER

The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be dependent on generated XML mapper files.

生成的对象是满足MyBatis 3.x版本的接口。这些接口只会依赖于xml mapper文件。

If the <context> targetRuntime is MyBatis3Simple the following predefined values can be used:
ANNOTATEDMAPPER The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be based on annotations and MyBatis 3.x SqlProviders. No XML mapper files will be generated.

The ANNOTATEDMAPPER requires MyBatis version 3.0.4 or higher.

XMLMAPPER The generated objects will be Java interfaces for the MyBatis 3.x mapper infrastructure. The interfaces will be dependent on generated XML mapper files.
targetPackage

This is the package where the generated interfaces and implementation classes will be placed. In the default generators, the property "enableSubPackages" controls how the actual package is calculated. If true, then the calculated package will be the targetPackage plus sub packages for the table‘s catalog and schema if they exist. If "enableSubPackages" is false (the default) then the calculated package will be exactly what is specified in the targetPackage attribute. MBG will create folders as required for the generated packages.

这个是生成接口和实现类放置的地方(package)。默认的生成器,“enableSubPackages”属性控制真正的package。如果是true,targetPackage会被放置在表目录(如果存在)下面。如果是false(默认),指定的package就是真正的存放路径。MBG将会创建文件夹为目标package。

Note: the package for implementation classes may be overridden by specifying the optional implementationPackage attribute as shown below.

targetProject

This is used to specify a target project for the generated interfaces and classes. When running in the Eclipse environment, this specifies the project and source folder where the objects will be saved. In other environments, this value should be an existing directory on the local file system. MBG will not create this directory if it does not exist.

这个属性是用来为生成的接口和类,指定一个目标功能。让运行在Eclipse环境下,这个指定project和source文件夹下,对象将会被保存。在其他环境中,该属性指定的值,应该是一个已经存在的文件夹,MBG不会创建该目录,如果文件夹不存在。

Child Elements

Supported Properties(支持的属性)

This table lists the properties of the default SQL Map generators that can be specified with the <property> child element:

Property NameProperty Values
enableSubPackages

This property is used to select whether MBG will generate different Java packages for the objects based on the catalog and schema of the introspected table.

该属性用来选择,MBG是否会生成不同的java package。

For example, suppose a table MYTABLE in schema MYSCHMA. Also suppose that the targetPackage attribute is set to "com.mycompany". If this property is true, the generated DAO interface and class for the table will be placed in the package "com.mycompany.myschema". If the property is false, the generated SQL Map will be placed in the "com.mycompany" schema.

例如,假设一个表MYTABLE在MYCHMA表空间下。同样的,假设targetPackage设置的值是“com.mycompany”。该属性为true,name生成的DAO接口、类会被放在“com.mycompany.myschema”下。如果该属性为false,生成的文件将会被放置在“com.mycompany”下。

The default value is false.

默认值为false

rootInterface

This property can be used to specify a super interface for all generated interface objects. This value may be overridden by specifying the rootInterface property on a Table configuration.

该属性用来为所有的对象指定一个父类接口。在指定table配置的rootInterface属性时,该值可能会被覆盖。

Important: MBG does not verify that the interface exists, or is a valid Java interface.

重要:MBG不会去验证接口是否存在、该接口是否有效。

If specified, the value of this property should be a fully qualified interface name (like com.mycompany.MyRootInterface).

若果指定,该值必须是接口的全名名称路径(如:com.mycompany.MyRootInterface)

useLegacyBuilder

If true, then annotated clients will use the SqlBuilder from MyBatis to generate dynamic SQL. With MyBatis 3.2 and later, that builder was deprecated in favor of the new SQL class. If false, MBG will generate clients that use the new SQL builder.

The default value is false.

Example

This element specifies that we always want to place generated interfaces and objects in the "‘test.model" package and that we want to use subpackages based on the table schema and catalog. It also specifies that we want to generate mapper interfaces that reference an XML configuration file for MyBatis3.

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


PS:这是本人,初步学习(差不多也搞了近一天),跑出来的结果,其实是有很多冗余,可能不符合你自己的需要,你可能还需修改很多配置,从写一些东西。多学习,多查博客~_~


个人重写注释的类(就是删掉了很多默认的注释,保留一个字段的注释)
package com.cls.all.great.mbg.comment;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.util.Properties;

public class MyCommentGenerator implements CommentGenerator {
    private Properties properties;
    private boolean suppressDate;
    private boolean suppressAllComments;

    public MyCommentGenerator() {
        super();
        properties = new Properties();
        suppressDate = false;
        suppressAllComments = false;
    }
    @Override
    public void addConfigurationProperties(Properties properties) {

    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
        // 添加字段的注释
        field.addJavaDocLine("/**");
        StringBuilder sb = new StringBuilder();
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString());
        field.addJavaDocLine("*/");
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) {

    }

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    @Override
    public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {

    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {

    }

    @Override
    public void addComment(XmlElement xmlElement) {

    }

    @Override
    public void addRootComment(XmlElement xmlElement) {

    }
}

 

它可以根据数据库中的表,来帮我们生成供mybatis使用使用实体类,xml和接口类。

Mybatis Generator学习

标签:sed   primary   connect   chm   sele   cat   相关   有用   result   

原文地址:https://www.cnblogs.com/longshun/p/14856583.html

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