实践MyBatis Generator(MBG)

MyBatis Generator (MBG) is a code generator for MyBatis or iBatis (>2.2.0).

可以生成如下内容:

  1. Java POJOs(domain),具体形式取决于defaultModelType,对应<javaModelGenerator>配置
  • 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)【Blob实体类】
  • a class to enable dynamic selects, updates, and deletes
  1. SQL Map XML Files,对应<sqlMapGenerator>配置
  • insert
  • insert selective
  • update by primary key
  • update by primary key selective
  • update by example (using a dynamic where clause)
  • update by example (using a dynamic where clause) selective
  • 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

备注:*Selective,为null的属性不加入sql(insert和update)

  1. Java client classes,对应<javaClientGenerator>配置
  • A mapper interface that works with the MyBatis 3.x mapper infrastructure

生成的内容注释中包含@mbg.generated,表明是生成的,重新生成时会先删除

generatorConfig.xml

<properties>

<classPathEntry>

定义JDBC驱动,推荐在classpath配置(比如pom.xml)

<context>

defaultModelType:生成model类型,默认值conditional,建议设置为flat

  • conditional:跟hierarchical类似,只是当表只有一个主键时,不生成基础实体类
  • flat:一个表一个domain类
  • hierarchical:生成多个类,主键一个,Blob字段共一个类,其他字段共一个类

targetRuntime:目标运行时,可取值包括:

MyBatis3:default

MyBatis3Simple:no by example methods

MyBatis3DynamicSql:MyBatis 3.4.2 and higher, Java 8 and higher, flat style, no Sql Mapper xml, annotated mapper,依赖org.mybatis.dynamic-sql:mybatis-dynamic-sql:1.0.0'

<properties>

autoDelimitKeywords

beginningDelimiter

endingDelimiter

javaFileEncoding

javaFormatter

xmlFormatter

<plugin>

<commentGenerator>

suppressDate:是否包含时间戳,默认值false,避免重复生成后时间戳的变化导致版本变化,建议设置为true

addRemarkComments:是否包含表和字段的备注,默认值false,建议设置为true

#### <connectionFactory>

<jdbcConnection>

<javaTypeResolver>

forceBigDecimals:是否强制DECIMALNUMERIC类型的字段转换为Java类型的java.math.BigDecimal,默认值为false

默认情况下的转换规则为:

  1. 如果精度>0或者长度>18,就会使用java.math.BigDecimal
  2. 如果精度=0并且10<=长度<=18,就会使用java.lang.Long
  3. 如果精度=0并且5<=长度<=9,就会使用java.lang.Integer
  4. 如果精度=0并且长度<5,就会使用java.lang.Short

<javaModelGenerator>

targetProject:绝对路径或相对路径,不自动创建目录,关于相对目录,不同运行方式规则不一样,命令行和maven方式,相对项目根目录,比如:src/main/java,eclipse plug-in方式,相对工作空间,前面追加项目名称,比如:sample-mybatis-generator-maven/src/main/java

targetPackage:会自动创建目录

<sqlMapGenerator>

<javaClientGenerator>

type:如果<context>targetRuntime是MyBatis3,则可取值有ANNOTATEDMAPPERMIXEDMAPPERXMLMAPPER

<table>

tableName:表名,支持SQL通配符,比如%

<generatedKey>

column:

identity:是否数据库自动自增生成,true一般适用于mysql或sql server,false一般适用于sequence之类的数据库,比如oracle等,默认值false

1
2
3
4
5
<!-- mysql -->
<generatedKey column="id" sqlStatement="MySql" identity="true" />
<!-- Oracle -->
<!-- {1}代表大写表名,{0}代表小写表名-->
<generatedKey column="id" sqlStatement="select SEQ_CITY.nextval from dual" />
1
2
3
4
5
6
7
8
9
10
11
12
13
<insert id="insert" parameterType="wang.angi.sample.mybatis.generator.eclipse.plugin.model.City">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Integer">
      select SEQ_CITY.nextval from dual
    </selectKey>
    insert into CITY (ID, CREATED_BY, COUNTRY, 
      STATE, NAME)
    values (#{id,jdbcType=DECIMAL}, #{createdBy,jdbcType=VARCHAR}, #{country,jdbcType=VARCHAR}, 
      #{state,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR})
  </insert>

sqlStatement:**

运行

命令行

项目下任意位置新建generatorConfig.xml,执行如下命令:

1
2
$ java -jar mybatis-generator-core-1.3.6.jar -configfile src/maing/resources/generatorConfig.xml -overwrite
$ java -cp mybatis-generator-core-x.x.x.jar org.mybatis.generator.api.ShellRunner -configfile generatorConfig.xml -overwrite

maven

添加mybatis-generator-maven-plugin(同时配置了JDBC驱动)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	<build>
		<plugins>
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.6</version>
                  <dependencies>
					<dependency>
						<groupId>mysql</groupId>
						<artifactId>mysql-connector-java</artifactId>
						<version>${mysql.version}</version>
					</dependency>
				</dependencies>
			</plugin>
		</plugins>
	</build>

src/main/resources目录下新建generatorConfig.xml,也可以通过属性自定义位置

依赖的驱动等可以定义在插件的<dependencies>下面,不用定义到<classPathEntry>

内容参考如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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="/media/angi/Resource/Maven-Repo/mysql/mysql-connector-java/5.1.45/mysql-connector-java-5.1.45.jar" />

	<context id="mysqlTables" defaultModelType="flat">
		<commentGenerator>
			<property name="suppressDate" value="true" />
			<property name="addRemarkComments" value="true"/>
		</commentGenerator>
		
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/test" userId="root"
			password="mysql">
		</jdbcConnection>

		<javaModelGenerator targetPackage="wang.angi.sample.mybatis.generator.maven.model"
			targetProject="src/main/java">
		</javaModelGenerator>

		<sqlMapGenerator targetPackage="wang.angi.sample.mybatis.generator.maven.mapper"
			targetProject="src/main/resources">
		</sqlMapGenerator>

		<javaClientGenerator type="XMLMAPPER"
			targetPackage="wang.angi.sample.mybatis.generator.maven.mapper"
			targetProject="src/main/java">
		</javaClientGenerator>

		<table tableName="city">
			<generatedKey column="id" sqlStatement="MySql" identity="true" />
		</table>
	</context>
</generatorConfiguration>
1
$ mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate

Eclipse plug-in

项目下任意目录新建generatorConfig.xml,右键generatorConfig.xml,选择Run As>Run MyBatis Generator

与maven生成的代码格式略不同,会导致版本管理工具识别出被修改过