美文网首页MiscroService
Mybatis Generator 分页查询插件开发

Mybatis Generator 分页查询插件开发

作者: linweiyu21 | 来源:发表于2017-07-01 19:59 被阅读0次

官方的 Mybatis Generator 工具生成的代码中没有分页查询的功能,如果想为生成的代码添加分页查询功能,我们可以为 Mybatis Generator 开发插件,使生成的代码中添加我们想要的 Method 与 SQL 语句.

在学习开发插件的过程中,我主要参考了如下文章.想要理解自定义插件的开发,建议先看看以下文章

  1. 理解MyBatis Generator Plugin
  2. 自定义MyBatis Generator Plugin
  3. Mybatis Generator Plugin 定制我需要的DAO
  4. Mybatis学习笔记九:自定义Generator Plugin

目标

本项目主要对 Mybatis Generator 生成的默认代码中添加分页查询一个方法与一个SQL语句.是对默认代码文件的扩展.
生成的结果如下:

分页查询方法 分页查询SQL语句

步骤

  1. 我们使用 Maven(version=3.5.0) 构建项目.使用如下命令
mvn archetype:generate -DgroupId=项目的groupId -DartifactId=项目的artifactId -DarchetypeArtifactId=maven-archetype-quickstart
  1. 为项目添加 Mybatis Generator 依赖.完整的项目依赖如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.linweiyu</groupId>
    <artifactId>PaginationPlugin</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>PaginationPlugin</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>[1.1.1,)</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>[1.3.5,)</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>mybatis-pagination-plugin-test</finalName>
        <plugins>
            <!-- 编译级别 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  1. 继承 org.mybatis.generator.api.PluginAdapter 类.通过重写其中的方法,即可完成我们需要功能.
    这个类的方法有很多,下面说说笔者学习过程中观察到的几个关键的方法.
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable)方法:通过重写此方法,可以在生成 Mapper.java 类时添加额外的方法.
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable)方法:通过重写此方法,可以在生成 Mapper.xml 文件时添加额外的 SQL 语句.
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable)方法:通过重写此方法,可以生成额外的 Java 类文件
    根据我们现在的需求,我们只需要重写 clientGenerated() , sqlMapDocumentGenerated() 两个方法即可.
  2. 重写 clientGenerated() 方法,生成额外的 Java 方法
    /**
     * 生成 List<实体类> selectByPage(@Param("offset") Long offset,@Param("limit") Long limit); 方法
     */
    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        boolean super_result = super.clientGenerated(interfaze, topLevelClass, introspectedTable);

            // 生成方法
            Method newMethod = new Method("selectByPage");
            // 设置方法类型
            newMethod.setVisibility(JavaVisibility.PUBLIC);

            // 设置方法返回值类型
            FullyQualifiedJavaType returnType = new FullyQualifiedJavaType("List<" + introspectedTable.getTableConfiguration().getDomainObjectName() + ">");
            newMethod.setReturnType(returnType);

            // 设置方法参数
            FullyQualifiedJavaType offsetJavaType = new FullyQualifiedJavaType("Long");
            Parameter offsetParameter = new Parameter(offsetJavaType, "offset");
            offsetParameter.addAnnotation("@Param(\"offset\")");
            newMethod.addParameter(0, offsetParameter);

            FullyQualifiedJavaType limitJavaType = new FullyQualifiedJavaType("Long");
            Parameter limitParameter = new Parameter(limitJavaType, "limit");
            limitParameter.addAnnotation("@Param(\"limit\")");
            newMethod.addParameter(1, limitParameter);

            // 添加相应的包
            interfaze.addImportedType(new FullyQualifiedJavaType(("org.apache.ibatis.annotations.Param")));
            interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List"));
            interfaze.addMethod(newMethod);

            return true;
        }
        return super_result;
    }
  1. 重写 sqlMapDocumentGenerated() 方法,生成额外的 SQL 语句
/**
     * 生成如下的分页查询sql语句
     * <select id="selectByPage" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List"/> FROM 表名 LIMIT #{offset}, #{limit} </select>
     */
    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        boolean super_result = super.sqlMapDocumentGenerated(document, introspectedTable);

        if (isGeneratePagination(introspectedTable) && super_result) {
            XmlElement select = new XmlElement("select");
            select.addAttribute(new Attribute("id", "selectByPage"));
            select.addAttribute(new Attribute("resultMap", "BaseResultMap"));
            select.addElement(new TextElement("SELECT <include refid=\"Base_Column_List\" /> FROM " + introspectedTable.getFullyQualifiedTableNameAtRuntime() + " LIMIT #{offset},#{limit}"));
            XmlElement parentElement = document.getRootElement();
            parentElement.addElement(select);
            return true;
        }

        return super_result;
    }

说明

在以上两个方法中,关键的地方在于使用 Mybatis Generator 中定义的类.
如:org.mybatis.generator.api.dom.java.Method类,这个类代表了 Mapper.java 文件中的一个方法.
大家可以查考 MyBatis Generator 的文档与源码,查阅这些类的定义,这在开发生成额外 Java 文件时十分有用.

结束

通过重写以上两个方法,就可以实现我们此次的目标了.关于如何使用自己开发的插件与获取本项目的源码,可以在 Github 上查看本项目.
在 Github 上还有本人的另一个插件项目,可以实现生成额外的 Java 文件,参考这个插件,我们可以生成任何我们想要的 Java 类!
时间水平有限,如果不足或错误之处,请多多包涵!

相关文章

网友评论

    本文标题:Mybatis Generator 分页查询插件开发

    本文链接:https://www.haomeiwen.com/subject/nulgcxtx.html