前言
MyBatis Generator(MBG)是MyBatis 和iBATIS的代码生成器。可以生成简单CRUD操作的XML配置文件、Mapper文件(DAO接口)、实体类。实际开发中能够有效减少程序员的工作量,甚至不用程序员手动写sql。
mybatis-generator有多种用法:命令行、maven插件等。命令行方式通常要把相关jar包下载到本地,再使用java -jar 运行。方便起见,本文演示使用maven插件的方式。
操作步驟
mybatis-generator有三种用法:命令行、eclipse插件、maven插件。个人觉得maven插件最方便,可以在eclipse/intellij idea等ide上可以通用。此处只介绍maven插件的使用方法。
添加依赖
在需要生成代码的模块pom文件中添加如下依赖,一般在在dao模块下生成代码。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
这两个依赖下载到本地仓库,备用。
添加maven插件,具体如下。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<configurationFile>src/main/resources/mybatis/generator/generatorConfig.xml</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
准备generatorConfig.xml
generator.properties
用于抽取公共配置或便于修改的属性Key
generatorConfig.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>
<!-- 引入配置文件 -->
<properties resource="mybatis/generator/generator.properties"/>
<!--需要指定本地Jar,可用当前Maven本地仓库下的Jar, mysql 连接数据库jar 这里选择自己本地位置-->
<classPathEntry location="/Users/simon/.m2/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar"/>
<context id="testTables" targetRuntime="MyBatis3">
<!-- mysql关键字处理 -->
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!--设置生成的Java文件的编码格式-->
<property name="javaFileEncoding" value="UTF-8"></property>
<!--格式化java代码-->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"></property>
<!--格式化xml代码-->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"></property>
<!--javaBean生成toString() 方法-->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 自动生成注释 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/spring_demo?useUnicode=true&characterEncoding=utf-8"
userId="root"
password="Xiele">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.example.start.springdemo.mybatis.generator"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置
如果maven工程只是单独的一个工程,targetProject="src/main/java"
若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
targetProject="ecps-manager-mapper",下同-->
<sqlMapGenerator targetPackage="mybatis.generator.sqlmap"
targetProject="src/main/resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.start.springdemo.mybatis.generator"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="spring_user" mapperName="SpringUserDao" domainObjectName="SpringUserDO"
enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
替换mybatis-generator-core.jar包
如果没有特殊需要,可以忽略这一步。
由于mybatis generator在生成XML文件时,会默认生成jdbcType和parameterType,而且在脚本语言中也带有jdbcType,本身来讲这个不是什么问题,但是如果遇到传入的对象是parameterType的子类对象,并且在脚本语言中用到了子类对象特有属性时,就会出现找不到属性的异常了。并且生成的DO文件注释也不符合规范。所以通过反编译重新打包的方式,对源码做了简单的修改,去掉了jdbcType和parameterType,将DO文件注释改为符合规范的风格。
只需用下文附件中的mybatis-generator-core-1.3.7.jar 替换本地仓库 org/mybatis/generator/mybatis-generator-core/1.3.7 目录下的 mybatis-generator-core-1.3.7.jar 即可。
mybatis-generator-core-1.3.7.jar
运行maven插件
通过IDEA执行
自动生成的代码示例
DAO&DO
package com.example.start.springdemo.mybatis.generator;
public interface SpringUserDao {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
int insert(SpringUserDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
int insertSelective(SpringUserDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
SpringUserDO selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
int updateByPrimaryKeySelective(SpringUserDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
int updateByPrimaryKey(SpringUserDO record);
}
package com.example.start.springdemo.mybatis.generator;
/**
* @author wb-jc582827
* @version 1.0: com.example.start.springdemo.mybatis.generator.SpringUserDao.java, v 0.1 2020-06-04 17:51:18 wb-jc582827 Exp $
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table spring_user
*/
public class SpringUserDO {
/**
* This property corresponds to db column <tt>id</tt>
*/
private Long id;
/**
* This property corresponds to db column <tt>name</tt>
*/
private String name;
/**
* This property corresponds to db column <tt>age</tt>
*/
private Byte age;
/**
* Getter method for property <tt>id</tt>
*
* @return property value of id
*/
public Long getId() {
return id;
}
/**
* Setter method for property <tt>id</tt>
*
* @param id value to be assigned to property id
*/
public void setId(Long id) {
this.id = id;
}
/**
* Getter method for property <tt>name</tt>
*
* @return property value of name
*/
public String getName() {
return name;
}
/**
* Setter method for property <tt>name</tt>
*
* @param name value to be assigned to property name
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* Getter method for property <tt>age</tt>
*
* @return property value of age
*/
public Byte getAge() {
return age;
}
/**
* Setter method for property <tt>age</tt>
*
* @param age value to be assigned to property age
*/
public void setAge(Byte age) {
this.age = age;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table spring_user
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", age=").append(age);
sb.append("]");
return sb.toString();
}
}
SqlMap
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.start.springdemo.mybatis.generator.SpringUserDao">
<resultMap id="BaseResultMap" type="com.example.start.springdemo.mybatis.generator.SpringUserDO">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="age" property="age" />
</resultMap>
<sql id="Base_Column_List">
id, `name`, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from spring_user
where id = #{id}
</select>
<delete id="deleteByPrimaryKey">
delete from spring_user
where id = #{id}
</delete>
<insert id="insert">
insert into spring_user (id, `name`, age)
values (#{id}, #{name}, #{age})
</insert>
<insert id="insertSelective">
insert into spring_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
`name`,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="name != null">
#{name},
</if>
<if test="age != null">
#{age},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective">
update spring_user
<set>
<if test="name != null">
`name` = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
where id = #{id}
</update>
<update id="updateByPrimaryKey">
update spring_user
set `name` = #{name},
age = #{age}
where id = #{id}
</update>
</mapper>