MyBatis--拦截器实现分页

主要内容:

MyBatis--拦截器实现分页


MyBatis四大对象及插件原理:

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页


MyBatis插件开发:

MyBatis--拦截器实现分页

测试:定义一个插件类:

MyFirstInterceptor :一定继承自Interceptor类,重写里面的方法

package com.mooc.mybatis.interceptor;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.Properties;

/**
 * 插件签名,告诉mybatis单钱插件用来拦截那个对象的哪个方法
 */
@Intercepts({
        @Signature(type = ResultSetHandler.class,method ="handleResultSets",args = Statement.class)

})
public class MyFirstInterceptor implements Interceptor {

    //拦截目标对象的目标方法
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("first plugin Intercept :"+invocation.getTarget());
        System.out.println(invocation.getMethod());
        System.out.println(invocation.getArgs());

        Object object=invocation.proceed();
        return object;
    }

    //包装目标对象 为目标对象创建代理对象的
    public Object plugin(Object o) {
        System.out.println("first plugin :"+o);
        return Plugin.wrap(o,this);
    }

    public void setProperties(Properties properties) {
        System.out.println("first plugin :"+properties);

    }
}

在配置文件对新创建的插件类进行配置:

	<plugins>
		<!--<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>-->

		<plugin interceptor="com.mooc.mybatis.interceptor.MyFirstInterceptor">
			<property name="hello" value="world"></property>
		</plugin>

		<plugin interceptor="com.mooc.mybatis.interceptor.MySecondInterceptor">
		</plugin>

	</plugins>

插件签名:

/**
 * 插件签名,告诉mybatis单钱插件用来拦截那个对象的哪个方法
 */
@Intercepts({
        @Signature(type = ResultSetHandler.class,method ="handleResultSets",args = Statement.class)

})

多插件开发详解:

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页


分页原理:

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页

MyBatis--拦截器实现分页


PageHelper:

github地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/en/HowToUse.md

使用PageHelper:在maven里

步骤1、pom.xml添加依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>x.x.x</version>
</dependency>

步骤2、修改mybatis-config.xml配置文件

<!-- 
    In the configuration file, 
    plugins location must meet the requirements as the following order:
    properties?, settings?, 
    typeAliases?, typeHandlers?, 
    objectFactory?,objectWrapperFactory?, 
    plugins?, 
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- config params as the following -->
        <property name="param1" value="value1"/>
	</plugin>
</plugins>

步骤3、在代码中使用:有多种方式,建议使用这种

//2. use static method startPage
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1);