MybatisGenerator自动生成代码(包含属性注释)

应翰飞
2023-12-01

1、创建generatorConfig.xml文件 (位于resources目录下)

<?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>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 注释生成配置 -->
        <commentGenerator>
            <!-- 是否阻止生成的注释中带有时间戳,默认false -->
            <property name="suppressDate" value="true"/>
            <!-- 是否阻止生成注释,默认false -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 数据库连接配置 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"
                        userId="root"
                        password="root">
            <!-- 将其配置为true可以解决找生成文件缺少 xxxByPrimaryKey 的问题 -->
            <property name="useInformationSchema" value="true"/>
        </jdbcConnection>

        <javaTypeResolver>
            <!-- 控制是否强制DECIMAL和NUMERIC类型的字段转换为Java类型的java.math.BigDecimal,默认值为false
                 如果精度>0或者长度>18,就会使用java.math.BigDecimal
                 如果精度=0并且10<=长度<=18,就会使用java.lang.Long
                 如果精度=0并且5<=长度<=9,就会使用java.lang.Integer
                 如果精度=0并且长度<5,就会使用java.lang.Short
                 默认false -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 实体类生成配置 -->
        <javaModelGenerator targetPackage="com.lbb.model.bean" targetProject="D:\ideaprojects\excelpoi\src\main\java">
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对查询结果进行trim操作,体现在setter方法中 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- xml生成配置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="D:\ideaprojects\excelpoi\src\main\resources">
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- Mapper生成配置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.lbb.mapper" targetProject="D:\ideaprojects\excelpoi\src\main\java">
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 作用的表 -->
        <table tableName="role_info" domainObjectName="RoleInfo"
               enableInsert="true"
               enableDeleteByPrimaryKey="true"
               enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true"
               enableCountByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               enableUpdateByExample="false">
        </table>
    </context>
</generatorConfiguration>

2、pom.xml配置中添加下面这两个jar包

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>

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

3、在实例的属性上自动生成注释的扩展类

package com.lbb.config;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;

public class MyCommentGenerator extends DefaultCommentGenerator {

    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        if (StringUtils.isBlank(introspectedColumn.getRemarks())) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        field.addJavaDocLine("/**");
        sb.append(" * ");
        sb.append(introspectedColumn.getRemarks());
        field.addJavaDocLine(sb.toString().replace("\n", " "));
        field.addJavaDocLine(" */");
    }
}

4、main方法

package com.lbb;

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

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MybatisGeneratorRun {
    public static void main(String[] args) throws Exception {
        MybatisGeneratorRun app = new MybatisGeneratorRun();

        System.out.println(app.getClass().getResource("/").getPath());
        app.generator();
        System.out.println(System.getProperty("user.dir"));
    }

    public void generator() throws Exception {

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(resourceAsStream);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);

        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

5、执行MybatisGeneratorRun中的main方法,触发代码的自动生成。

下面是生成后的代码:

RoleInfo.class

package com.lbb.model.bean;

import java.util.Date;

public class RoleInfo {
    private Long id;

    /**
     * 角色名称
     */
    private String roleName;

    /**
     * 角色类别
     */
    private String roleCategory;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 创建人id
     */
    private Long createId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName == null ? null : roleName.trim();
    }

    public String getRoleCategory() {
        return roleCategory;
    }

    public void setRoleCategory(String roleCategory) {
        this.roleCategory = roleCategory == null ? null : roleCategory.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Long getCreateId() {
        return createId;
    }

    public void setCreateId(Long createId) {
        this.createId = createId;
    }
}

RoleMapper.class

package com.lbb.mapper;

import com.lbb.model.bean.RoleInfo;

public interface RoleInfoMapper {
    int deleteByPrimaryKey(Long id);

    int insert(RoleInfo record);

    int insertSelective(RoleInfo record);

    RoleInfo selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(RoleInfo record);

    int updateByPrimaryKey(RoleInfo record);
}

RoleMapper.xml

<?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.lbb.mapper.RoleInfoMapper" >
  <resultMap id="BaseResultMap" type="com.lbb.model.bean.RoleInfo" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="role_name" property="roleName" jdbcType="VARCHAR" />
    <result column="role_category" property="roleCategory" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="create_id" property="createId" jdbcType="BIGINT" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, role_name, role_category, create_time, create_id
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from role_info
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from role_info
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.lbb.model.bean.RoleInfo" >
    insert into role_info (id, role_name, role_category, 
      create_time, create_id)
    values (#{id,jdbcType=BIGINT}, #{roleName,jdbcType=VARCHAR}, #{roleCategory,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP}, #{createId,jdbcType=BIGINT})
  </insert>
  <insert id="insertSelective" parameterType="com.lbb.model.bean.RoleInfo" >
    insert into role_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="roleName != null" >
        role_name,
      </if>
      <if test="roleCategory != null" >
        role_category,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="createId != null" >
        create_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="roleName != null" >
        #{roleName,jdbcType=VARCHAR},
      </if>
      <if test="roleCategory != null" >
        #{roleCategory,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createId != null" >
        #{createId,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.lbb.model.bean.RoleInfo" >
    update role_info
    <set >
      <if test="roleName != null" >
        role_name = #{roleName,jdbcType=VARCHAR},
      </if>
      <if test="roleCategory != null" >
        role_category = #{roleCategory,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="createId != null" >
        create_id = #{createId,jdbcType=BIGINT},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.lbb.model.bean.RoleInfo" >
    update role_info
    set role_name = #{roleName,jdbcType=VARCHAR},
      role_category = #{roleCategory,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      create_id = #{createId,jdbcType=BIGINT}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>
 类似资料: