前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MyBatis-Generator例子简介

MyBatis-Generator例子简介

作者头像
doper
发布2022-09-26 17:50:10
1.1K0
发布2022-09-26 17:50:10
举报

MyBatis-Generator例子简介

mybatis-generator官方文档: http://mybatis.org/generator/index.html

例子代码参考: mall

1. 运行MyBatis Generator(MBG)

这部分文档已经说的很清楚了,这里列举java运行代码

image-20220423210040200
image-20220423210040200

1.1. 基于XML配置文件运行

代码语言:javascript
复制
List<String> warnings = new ArrayList<String>();	//这里存储运行过程中的警告信息
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");	//这里是配置文件
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);

1.2. 基于Java配置代码运行

代码语言:javascript
复制
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
Configuration config = new Configuration();

//   ... fill out the config object as appropriate...

DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);

2. XML配置文件

官方文档对XML的描述十分详细,这里仅列举自己学习过程中碰到的,代码来源于mall项目:

代码语言:javascript
复制
<?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>	
    <!-- 用来指定用于解析外部配置文件里面的属性,外部配置文件的属性可以用${property}来引用	-->
    <properties resource="generator.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <!-- plugin用来定义插件,可选的插件文档有详细列出来:http://mybatis.org/generator/reference/plugins.html -->
        <!-- 为模型生成序列化方法-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!-- 为生成的Java模型创建一个toString方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--生成文件时覆盖原mapper.xml,因为默认多次运行生成的代码是追加到原文件而不是覆盖,因此要指定这个插件-->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
        <!-- commentGenerator用来定义注释生成器的属性,其可用于Java字段,方法,XML元素的注释生成 -->
        <!-- 可自定义注释生成器,必须要实现 org.mybatis.generator.api.CommentGenerator 接口 -->
        <!-- 若不指定type,则默认使用 org.mybatis.generator.internal.DefaultCommentGenerator -->
        <commentGenerator type="cn.doper.mall.CommentGenerator">
            <!-- 是否去除mybatis-generator默认的自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 是否去掉自动生成的注释中添加生成日期, true: 是, false:否 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否在生成的注释中显示对应数据库table中的字段名, true: 是, false: 否 -->
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <!-- 配置数据库属性,这里传入<properties>外部配置文件的属性 -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <!-- 生成Java模型的包名与路径,这些模型是与数据库表中字段相对应的类,用来操作数据库,会生成xxx.class和xxxExample.class,Example类一般用来构造复杂查询 -->
        <javaModelGenerator targetPackage="cn.doper.mall.model" targetProject="mall-mbg/src/main/java"/>
        <!-- 生成对应的mapper.xml文件 -->
        <sqlMapGenerator targetPackage="cn.doper.mall.mapper" targetProject="mall-mbg/src/main/resources"/>
        <!-- 生成对应的Mapper接口,与mapper.xml文件对应,XMLMAPPER表示生成对应Mybatis3的Java接口-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.doper.mall.mapper" targetProject="mall-mbg/src/main/java"/>
        <!-- 指定对哪些表生成代码,%表示全部 -->
        <table tableName="%">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>

MBG自动生成的注释如下所示:

image-20220423210906552
image-20220423210906552

3. 注释生成器

这里使用了自定义的注释生成器,主要生成swagger相关的注解,代码来源于mall项目:

代码语言:javascript
复制
package cn.doper.mall;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;  // 默认不显示table字段注释
    private static final String EXAMPLE_SUFFIX = "Example";
    private static final String MAPPER_SUFFIX = "Mapper";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME = "io.swagger.annotations.ApiModelProperty";

    /**
     * 设置用户配置的参数
     * 得到在xml中配置在<commentGenerator>中的参数properties
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        // 配置文件的addRemarkComments属性
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));	
    }

    /**
     * 给字段添加 @APiModelProperty注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();       //返回数据库字段的注释内容,没的话则为""
        //根据参数和备注信息判断是否添加swagger注解信息
        // 这里为若数据库字段有注释,则生成对应的 @ApiModelProperty(value = "{注释}") 注解
        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
            //数据库中特殊字符需要转义,防止注释字段中出现双引号(")这个符号
            if (remarks.contains("\"")) {
                remarks = remarks.replace("\"", "'");
            }
            //给model的字段添加swagger注解
            field.addJavaDocLine("@ApiModelProperty(value = \"" + remarks + "\")");
        }
    }


    /**
     * 在生成的每个文件添加swagger的包, import ...,如import io.swagger.annotations.ApiModelProperty;
     *
     * @param compilationUnit the compilation unit
     */
    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        // 只在model中的非Example添加swagger注解类的导入
        // 这是防止上述添加了@ApiModelProperty注解后却没有导入包的情况
        if (!compilationUnit.getType().getFullyQualifiedName().contains(MAPPER_SUFFIX) &&
                !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
        }
    }
}

4. MBG代码

代码来源于mall项目:

代码语言:javascript
复制
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG 执行过程中的警告信息
        List<String> warnings = new ArrayList<String>();
        //当生成的代码重复时,覆盖原代码
        boolean overwrite = true;
        //读取我们的 MBG 配置文件
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

5. 踩坑

在第2步的xml配置文件中有如下属性:

代码语言:javascript
复制
<javaModelGenerator targetPackage="cn.doper.mall.model" targetProject="mall-mbg/src/main/java"/>
<sqlMapGenerator targetPackage="cn.doper.mall.mapper" targetProject="mall-mbg/src/main/resources"/>
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.doper.mall.mapper" targetProject="mall-mbg/src/main/java"/>

springboot里,若targetProject若不配置程序运行的工作空间则会报错找不到对应路径,具体在idea解决方法为修改工作目录为父项目的目录。

image-20220423212408441
image-20220423212408441
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • MyBatis-Generator例子简介
  • 1. 运行MyBatis Generator(MBG)
    • 1.1. 基于XML配置文件运行
      • 1.2. 基于Java配置代码运行
      • 2. XML配置文件
      • 3. 注释生成器
      • 4. MBG代码
      • 5. 踩坑
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档