欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis(七) - Mybatis手写分页插件

程序员文章站 2022-06-28 17:42:52
Mybatis手写分页插件本篇文章是通过看视频学习总结的内容, 如有错误的地方请谅解,并联系博主及时修改,谢谢您的阅读.官网的解释mybatis 官网前言: 在官网中描述,Mybatis只支持拦截四大对象Executor、ParameterHandler、ResultSetHandler、StatementHandler 且每个对象被拦截的方法是有限的,具体参照官网,在本篇博客中主要讲解对 Executor 对象的 query 方法进行拦截,在官网中提供了一个小 dome,本篇博客则是根据小 d...

Mybatis手写分页插件

本篇文章是通过看视频学习总结的内容, 如有错误的地方请谅解,并联系博主及时修改,谢谢您的阅读.

官网的解释

官网地址:mybatis 官网
源码地址:github 插件源码

前言: 在官网中描述,Mybatis只支持拦截四大对象Executor、ParameterHandler、ResultSetHandler、StatementHandler 且每个对象被拦截的方法是有限的,具体参照官网,在本篇博客中主要讲解对 Executor 对象的 query 方法进行拦截,在官网中提供了一个小 dome,本篇博客则是根据小 dome 写一个 类似 github 上很火的 PageHelper 插件

一、准备工作
  • 1 引入依赖
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <!--<version>5.1.21</version>-->
    <version>8.0.15</version>
</dependency>
  • 2 创建数据库和表
CREATE TABLE `t_user` (
  `id` varchar(10) NOT NULL COMMENT '主键',
  `user_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名称',
  `password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
  `address` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '居住地址',
  `phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户电话',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
  • 3 创建mybatis-config.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="db.properties"></properties>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <!-- 控制全局缓存(二级缓存),默认 true-->
        <setting name="cacheEnabled" value="false"/>
        <!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。默认 false  -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!-- 当开启时,任何方法的调用都会加载该对象的所有属性。默认 false,可通过select标签的 fetchType来覆盖-->
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="localCacheScope" value="SESSION"/>
    </settings>

    <typeAliases>
        <typeAlias alias="user" type="com.example.mybatis.domain.User" />
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/><!-- 单独使用时配置成MANAGED没有事务 -->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>

</configuration>
  • 4 db.properties
## mysql 8.x 版本
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root
  • 5 创建 User 对象
@Setter
@Getter
@ToString
public class User implements Serializable {

    private String id;
    private String username;
    private String password;
    private String address;
    private String phone;
}
  • 6 UserMapper.java
public interface UserMapper {
    /**
     * 获取分页
     * @param phone 电话
     * @return
     */
    User selectUserById(String id);
}
  • 7 UserMapper.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.example.mybatis.mapper.UserMapper">
    <select id="getUserPage" resultType="user">
        SELECT id, user_name, password, address, phone FROM t_user where id= #{id}
    </select>
</mapper>
二、手写插件
  • 1 根据官网描述,插件必须要继承 Interceptor 接口,并且类上需要添加注释 @Interceptors 注解
  • 2 mybatis-config.xml 中加入插件标签,启用插件
package com.example.mybatis.plugin.intercepter;

import com.example.mybatis.plugin.util.Page;
import com.example.mybatis.plugin.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * <p>
 * 自定义分页插件拦截器
 * </p>
 *
 * @author zyred
 * @createTime 2020/9/15 14:05
 **/
@Slf4j
@Intercepts(
        {
                @Signature(
                        // 拦截executor类, 拦截的方法 query
                        type = Executor.class, method = "query",
                        // Invocation 对象中 args参数类型
                        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
                )
        }
)
public class PageInterceptor implements Interceptor {

    /**
     * 真正拦截执行的方法
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("page plugin running ...");
        Object[] args = invocation.getArgs();

        MappedStatement ms = (MappedStatement) args[0];

        BoundSql boundSql = ms.getBoundSql(args[1]);

        Page page = PageUtil.getPage();

        // 无需分页
        if (page == null) {
            return invocation.proceed();
        }

        // 需要分页,则修改sql逻辑
        String sql = boundSql.getSql();
        log.info("before sql : {}", sql);
        String limit = String.format(" limit %s, %s", page.getOffset(), page.getLimit());
        sql += limit;
        log.info("after sql : {}", sql);

        // 利用反射,重新把SqlSource对象写入到MappedStatment对象中
        SqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), sql, boundSql.getParameterMappings());
        Field field = MappedStatement.class.getDeclaredField("sqlSource");
        field.setAccessible(true);
        field.set(ms, sqlSource);

        // 执行被拦截的方法
        Object result = invocation.proceed();
        PageUtil.remove();
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
  • 3 分页工具类

/**
 * <p>
 *      分页工具
 * </p>
 *
 * @author zyred
 * @createTime 2020/9/15 15:21
 **/
public class PageUtil {

    private static final ThreadLocal<Page> local_page = new ThreadLocal<>();

    public static void setPage(int offset, int limit){
        Page page = new Page();
        page.setOffset(offset);
        page.setLimit(limit);
        local_page.set(page);
    }

    public static void remove(){
        local_page.remove();
    }
    
    public static Page getPage(){
        return local_page.get();
    }
}
  • 4 Page对象
package com.example.mybatis.plugin.util;

import lombok.Getter;
import lombok.Setter;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @createTime 2020/9/15 15:56
 **/
@Setter
@Getter
public class Page {

    private int offset = 0;

    private int limit = 10;
    
}
  • 5 mybatis-config.xml 中加上插件的配置
<!-- 配置插件 -->
<plugins>
    <plugin interceptor="com.example.mybatis.plugin.intercepter.PageInterceptor">
        <property name="gupao" value="betterme" />
    </plugin>
    <plugin interceptor="com.example.mybatis.plugin.intercepter.LevelOfTableInterceptor">
        <property name="gupao" value="betterme" />
    </plugin>
    <!--<plugin interceptor="com.gupaoedu.interceptor.MyPageInterceptor">
    </plugin>-->
</plugins>
  • 6 Juint 测试
package com.example.mybatis;

import com.example.mybatis.domain.Fee;
import com.example.mybatis.domain.User;
import com.example.mybatis.mapper.FeeMapper;
import com.example.mybatis.mapper.UserMapper;
import com.example.mybatis.plugin.util.PageUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

public class MyBatisTest {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void prepare() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void customPagePlugin() {
        // 自定义的插件
        PageUtil.setPage(0, 4);
        SqlSession session = this.sqlSessionFactory.openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> page = mapper.getUserPage("10086");
        System.out.println(page.size());
        page.stream().forEach(System.out::println);
    }
}
  • 7 不使用插件执行
==>  Preparing: SELECT id, username, password, address, phone FROM t_user where phone = ? 
==> Parameters: 10086(String)
<==    Columns: id, username, password, address, phone
<==        Row: 1, ZYRED1, 123456, 北京, 10086
<==        Row: 2, ZYRED3, 123456, 上海, 10086
<==        Row: 3, ZYRED3, 123456, 广州, 10086
<==        Row: 4, ZYRED4, 123456, 深圳, 10086
<==        Row: 5, ZYRED5, 123456, 杭州, 10086
<==      Total: 5
5
  • 8 使用插件执行
==>  Preparing: SELECT id, username, password, address, phone FROM t_user where phone = ? limit 0, 4 
==> Parameters: 10086(String)
<==    Columns: id, username, password, address, phone
<==        Row: 1, ZYRED1, 123456, 北京, 10086
<==        Row: 2, ZYRED3, 123456, 上海, 10086
<==        Row: 3, ZYRED3, 123456, 广州, 10086
<==        Row: 4, ZYRED4, 123456, 深圳, 10086
<==      Total: 4
4
  • 9 不足,没有再次获取数据库中总条数
总结

mybatis 的插件开发其实并不难,只要掌握了应该拦截哪个方法,使用自己的逻辑去处理对应的逻辑就可以。

本文地址:https://blog.csdn.net/qq_38800175/article/details/108714189

相关标签: mybatis