• MyBatis加强(2)~mybatis 插件开发 【分页插件PageHelper】




    ## 一、插件介绍【动态代理】

    1、插件【动态代理】:mybatis 允许在已经映射的语句的执行过程的某个时机进行拦截增强的机制。


    2、mybatis中的组件动态代理的运用:

    MyBatis 在四大组件对象的创建过程中,都会有插件进行调用执行。

    我们可以利用动态机制对目标对象实施拦截增强操作,也就是在目标对象执行目标方法之前进行拦截增强的效果。

    • Excutor(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
    • Parameter(update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
    • RestultSetHandler(handleResultSets, handleOutputParameters)
    • StatementHandler(prepare, parameterize, batch, update, query)

    3、插件开发步骤:

    (1)编写插件实现Intercetor接口,并使用@Intercepts 注解完成插件签名

    (2)在全局配置文件中使用 元素注册插件

    //标注对哪个组件的哪个方法做拦截增强
    //对组件ResultSetHandler中的handleResultSets(Statement st)方法进行拦截增强
    @Intercepts({@Signature(
    		  type= ResultSetHandler.class ,//
    		  method = "handleResultSets",//
    		  args = {Statement.class})})//
    public class DemoIntercetor implements Interceptor{
    	
    	//如何增强
    	@Override
    	public Object intercept(Invocation invocation) throws Throwable {
    		System.out.println("拦截增强啦");
    		return invocation.proceed();//放行
    	}
    }
    
    <!--全局配置文件-->
    <!-- 注册拦截器 -->
    <plugins>
     	<plugin interceptor="com.shan.mybatis.plugin.DemoIntercetor"></plugin>
    </plugins>
    

    二、MyBatis 分页插件-PageHelper


    1、依赖:

    • jsqlparser.jar
    • pagehelper.jar

    2、配置,在全局映射文件配置分页插件:

    <!-- 全局映射文件 -->
    <!-- 配置插件 -->
    <plugins>
    	<!-- com.github.pagehelper为PageHelper类所在包名 -->
    	<plugin interceptor="com.github.pagehelper.PageInterceptor">
    	<!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
    		<property name="helperDialect" value="mysql" />
    	</plugin>
    </plugins>
    

    ■ 配置完成,只需要在映射文件书写查询结果集的元素,然后测试的时候添加上:PageHelper.startPage(3, 3); 就实现了分页效果

    //mapper接口
    public interface EmployeeMapper {
    	List<Employee> queryList();
    }
    
    <!-- 映射文件 -->
    <select id="queryList" resultType="Employee">
    	select  id, name, sn, salary from employee	
    </select>
    
    //测试
    @Test
    public void testPagePlugin() throws Exception {
    	EmployeeMapper employeeMapper = MyBatisUtil.getMapper(EmployeeMapper.class);
    	PageHelper.startPage(3, 3);
    	List<Employee> emps = employeeMapper.queryList();
    	for (Employee employee : emps) {
    		System.out.println(employee);
    	}
        System.out.println("============================================================");
        //测试分页插件的接口PageInfo,好比是咱的PageResult
    	PageInfo pageInfo = new PageInfo(emps);
    	System.out.println(pageInfo.getTotal());
    	System.out.println(pageInfo.getList());
    }
    

  • 相关阅读:
    联合主键SQL 联合索引
    SQL 对decimal类型转换为int类型
    SQL获取当前时间月份为两位数
    SQL 对结果集进行分组排序过滤重复数据 ROW_NUMBER
    SQL自动流水号函数
    SQL 索引创建
    .Net三层架构
    2016年你应该学习的语言和框架(转)
    MongoDB学习笔记(转)
    干货分享:让你分分钟学会 javascript 闭包(转)
  • 原文地址:https://www.cnblogs.com/shan333/p/15898070.html
Copyright © 2020-2023  润新知