前言

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模块下生成代码。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>8.0.17</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mybatis.generator</groupId>
  8. <artifactId>mybatis-generator-core</artifactId>
  9. <version>1.3.7</version>
  10. </dependency>

这两个依赖下载到本地仓库,备用。
添加maven插件,具体如下。

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. </plugin>
  7. <plugin>
  8. <groupId>org.mybatis.generator</groupId>
  9. <artifactId>mybatis-generator-maven-plugin</artifactId>
  10. <version>1.3.7</version>
  11. <configuration>
  12. <configurationFile>src/main/resources/mybatis/generator/generatorConfig.xml</configurationFile>
  13. </configuration>
  14. </plugin>
  15. </plugins>
  16. </build>

准备generatorConfig.xml

一般放到dao模块或测试模块的单独目录下,如:
image.png

generator.properties

用于抽取公共配置或便于修改的属性Key

generatorConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <!-- 引入配置文件 -->
  7. <properties resource="mybatis/generator/generator.properties"/>
  8. <!--需要指定本地Jar,可用当前Maven本地仓库下的Jar, mysql 连接数据库jar 这里选择自己本地位置-->
  9. <classPathEntry location="/Users/simon/.m2/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar"/>
  10. <context id="testTables" targetRuntime="MyBatis3">
  11. <!-- mysql关键字处理 -->
  12. <property name="autoDelimitKeywords" value="true"/>
  13. <property name="beginningDelimiter" value="`"/>
  14. <property name="endingDelimiter" value="`"/>
  15. <!--设置生成的Java文件的编码格式-->
  16. <property name="javaFileEncoding" value="UTF-8"></property>
  17. <!--格式化java代码-->
  18. <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"></property>
  19. <!--格式化xml代码-->
  20. <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"></property>
  21. <!--javaBean生成toString() 方法-->
  22. <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
  23. <!-- 自动生成注释 -->
  24. <commentGenerator>
  25. <property name="suppressDate" value="true"/>
  26. <property name="addRemarkComments" value="true"/>
  27. </commentGenerator>
  28. <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
  29. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  30. connectionURL="jdbc:mysql://127.0.0.1:3306/spring_demo?useUnicode=true&amp;characterEncoding=utf-8"
  31. userId="root"
  32. password="Xiele">
  33. </jdbcConnection>
  34. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
  35. NUMERIC 类型解析为java.math.BigDecimal -->
  36. <javaTypeResolver>
  37. <property name="forceBigDecimals" value="false"/>
  38. </javaTypeResolver>
  39. <!-- targetProject:生成PO类的位置 -->
  40. <javaModelGenerator targetPackage="com.example.start.springdemo.mybatis.generator"
  41. targetProject="src/main/java">
  42. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  43. <property name="enableSubPackages" value="false"/>
  44. <!-- 从数据库返回的值被清理前后的空格 -->
  45. <property name="trimStrings" value="true"/>
  46. </javaModelGenerator>
  47. <!-- targetProject:mapper映射文件生成的位置
  48. 如果maven工程只是单独的一个工程,targetProject="src/main/java"
  49. 若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
  50. targetProject="ecps-manager-mapper",下同-->
  51. <sqlMapGenerator targetPackage="mybatis.generator.sqlmap"
  52. targetProject="src/main/resources">
  53. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  54. <property name="enableSubPackages" value="false"/>
  55. </sqlMapGenerator>
  56. <!-- targetPackage:mapper接口生成的位置 -->
  57. <javaClientGenerator type="XMLMAPPER"
  58. targetPackage="com.example.start.springdemo.mybatis.generator"
  59. targetProject="src/main/java">
  60. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  61. <property name="enableSubPackages" value="false"/>
  62. </javaClientGenerator>
  63. <!-- 指定数据库表 -->
  64. <table tableName="spring_user" mapperName="SpringUserDao" domainObjectName="SpringUserDO"
  65. enableCountByExample="false"
  66. enableUpdateByExample="false" enableDeleteByExample="false"
  67. enableSelectByExample="false" selectByExampleQueryId="false">
  68. </table>
  69. </context>
  70. </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执行
image.png

自动生成的代码示例

DAO&DO

  1. package com.example.start.springdemo.mybatis.generator;
  2. public interface SpringUserDao {
  3. /**
  4. * This method was generated by MyBatis Generator.
  5. * This method corresponds to the database table spring_user
  6. */
  7. int deleteByPrimaryKey(Long id);
  8. /**
  9. * This method was generated by MyBatis Generator.
  10. * This method corresponds to the database table spring_user
  11. */
  12. int insert(SpringUserDO record);
  13. /**
  14. * This method was generated by MyBatis Generator.
  15. * This method corresponds to the database table spring_user
  16. */
  17. int insertSelective(SpringUserDO record);
  18. /**
  19. * This method was generated by MyBatis Generator.
  20. * This method corresponds to the database table spring_user
  21. */
  22. SpringUserDO selectByPrimaryKey(Long id);
  23. /**
  24. * This method was generated by MyBatis Generator.
  25. * This method corresponds to the database table spring_user
  26. */
  27. int updateByPrimaryKeySelective(SpringUserDO record);
  28. /**
  29. * This method was generated by MyBatis Generator.
  30. * This method corresponds to the database table spring_user
  31. */
  32. int updateByPrimaryKey(SpringUserDO record);
  33. }
  1. package com.example.start.springdemo.mybatis.generator;
  2. /**
  3. * @author wb-jc582827
  4. * @version 1.0: com.example.start.springdemo.mybatis.generator.SpringUserDao.java, v 0.1 2020-06-04 17:51:18 wb-jc582827 Exp $
  5. *
  6. * This class was generated by MyBatis Generator.
  7. * This class corresponds to the database table spring_user
  8. */
  9. public class SpringUserDO {
  10. /**
  11. * This property corresponds to db column <tt>id</tt>
  12. */
  13. private Long id;
  14. /**
  15. * This property corresponds to db column <tt>name</tt>
  16. */
  17. private String name;
  18. /**
  19. * This property corresponds to db column <tt>age</tt>
  20. */
  21. private Byte age;
  22. /**
  23. * Getter method for property <tt>id</tt>
  24. *
  25. * @return property value of id
  26. */
  27. public Long getId() {
  28. return id;
  29. }
  30. /**
  31. * Setter method for property <tt>id</tt>
  32. *
  33. * @param id value to be assigned to property id
  34. */
  35. public void setId(Long id) {
  36. this.id = id;
  37. }
  38. /**
  39. * Getter method for property <tt>name</tt>
  40. *
  41. * @return property value of name
  42. */
  43. public String getName() {
  44. return name;
  45. }
  46. /**
  47. * Setter method for property <tt>name</tt>
  48. *
  49. * @param name value to be assigned to property name
  50. */
  51. public void setName(String name) {
  52. this.name = name == null ? null : name.trim();
  53. }
  54. /**
  55. * Getter method for property <tt>age</tt>
  56. *
  57. * @return property value of age
  58. */
  59. public Byte getAge() {
  60. return age;
  61. }
  62. /**
  63. * Setter method for property <tt>age</tt>
  64. *
  65. * @param age value to be assigned to property age
  66. */
  67. public void setAge(Byte age) {
  68. this.age = age;
  69. }
  70. /**
  71. * This method was generated by MyBatis Generator.
  72. * This method corresponds to the database table spring_user
  73. */
  74. @Override
  75. public String toString() {
  76. StringBuilder sb = new StringBuilder();
  77. sb.append(getClass().getSimpleName());
  78. sb.append(" [");
  79. sb.append("Hash = ").append(hashCode());
  80. sb.append(", id=").append(id);
  81. sb.append(", name=").append(name);
  82. sb.append(", age=").append(age);
  83. sb.append("]");
  84. return sb.toString();
  85. }
  86. }

SqlMap

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.start.springdemo.mybatis.generator.SpringUserDao">
  4. <resultMap id="BaseResultMap" type="com.example.start.springdemo.mybatis.generator.SpringUserDO">
  5. <id column="id" property="id" />
  6. <result column="name" property="name" />
  7. <result column="age" property="age" />
  8. </resultMap>
  9. <sql id="Base_Column_List">
  10. id, `name`, age
  11. </sql>
  12. <select id="selectByPrimaryKey" resultMap="BaseResultMap">
  13. select
  14. <include refid="Base_Column_List" />
  15. from spring_user
  16. where id = #{id}
  17. </select>
  18. <delete id="deleteByPrimaryKey">
  19. delete from spring_user
  20. where id = #{id}
  21. </delete>
  22. <insert id="insert">
  23. insert into spring_user (id, `name`, age)
  24. values (#{id}, #{name}, #{age})
  25. </insert>
  26. <insert id="insertSelective">
  27. insert into spring_user
  28. <trim prefix="(" suffix=")" suffixOverrides=",">
  29. <if test="id != null">
  30. id,
  31. </if>
  32. <if test="name != null">
  33. `name`,
  34. </if>
  35. <if test="age != null">
  36. age,
  37. </if>
  38. </trim>
  39. <trim prefix="values (" suffix=")" suffixOverrides=",">
  40. <if test="id != null">
  41. #{id},
  42. </if>
  43. <if test="name != null">
  44. #{name},
  45. </if>
  46. <if test="age != null">
  47. #{age},
  48. </if>
  49. </trim>
  50. </insert>
  51. <update id="updateByPrimaryKeySelective">
  52. update spring_user
  53. <set>
  54. <if test="name != null">
  55. `name` = #{name},
  56. </if>
  57. <if test="age != null">
  58. age = #{age},
  59. </if>
  60. </set>
  61. where id = #{id}
  62. </update>
  63. <update id="updateByPrimaryKey">
  64. update spring_user
  65. set `name` = #{name},
  66. age = #{age}
  67. where id = #{id}
  68. </update>
  69. </mapper>