MyBatis 在四大组件对象的创建过程中,都会有插件进行调用执行。
我们可以利用动态机制对目标对象实施拦截增强操作,也就是在目标对象执行目标方法之前进行拦截增强的效果。
//标注对哪个组件的哪个方法做拦截增强//对组件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><!-- 全局映射文件 --><!-- 配置插件 --><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>//测试@Testpublic 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());}