mybatis pagehelper Mybatis pagehelper分页插件使用过程解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mybatis pagehelper Mybatis pagehelper分页插件使用过程解析

小白coder   2021-04-21 我要评论

这篇文章主要介绍了mybatis pagehelper分页插件使用过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

使用过mybatis的人都知道,mybatis本身就很小且简单,sql写在xml里,统一管理和优化。缺点当然也有,比如我们使用过程中,要使用到分页,如果用最原始的方式的话,1.查询分页数据,2.获取分页长度,也就是说要使用到两个方法才能完成分页。有没有更更好的分页方式的,pagehelper分页插件因此而诞生,他的原理是利用mybatis拦截器,在查询数据库的时候,拦截下SQL,然后进行修改,从而实现分页(如果你硬是想知道原理,mybatis拦截器,学习过后你就知道什么回事了)。

这篇博客先向大家展示怎么使用,过后有时间再讲他的实现原理。

1.添加maven依赖

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

2.在 Spring 配置文件中配置拦截器插件,也可以在mybatis的xml里面配置,但是两种配置不能同时出现,否则容易出现com.github.pagehelper.PageInterceptor插件出现空指针问题

在spring.xml中定义:

<!--配置SqlSessionFactory对象 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml" />
    <property name="typeAliasesPackage" value="com.aoChine.model.entity" />
    <property name="mapperLocations" value="classpath:mapper/*.xml" />

    <!-- 配置mybatis分页插件PageHelper -->
    <property name="plugins">
      <array>
        <bean class="com.github.pagehelper.PageInterceptor">
          <property name="properties">
            <!-- 什么都不配,使用默认的配置 -->
            <value></value>
          </property>
        </bean>
      </array>
    </property>
  </bean>

在mybatis-config.xml中定义

<plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
      <!-- 使用MySQL方言的分页 -->
      <property name="helperDialect" value="sqlserver"/><!--如果使用mysql,这里value为mysql-->
      <property name="pageSizeZero" value="true"/>
    </plugin>
 </plugins>

3.使用

a)写正常查询语句的接口

接口:

b)在service层调用接口,实现分页。

分页插件使用这样就使用完毕了,博客只是介绍了最简单的使用方法,如果需要了解更多内容

这个是开源社区上面的插件库地址:

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们