mybatis使用过程中,要使用到分页,如果用最原始的方式的话。

    1.查询分页数据。

    2.获取分页长度,也就是说要使用到两个方法才能完成分页。有没有更更好的分页方式的,pagehelper分页插件因此而诞生,他的原理是利用mybatis拦截器,在查询数据库的时候,拦截下SQL,然后进行修改,从而实现分页。

    1.添加maven依赖

    1. <dependency>
    2. <groupId>com.github.pagehelper</groupId>
    3. <artifactId>pagehelper</artifactId>
    4. <version>5.0.0</version>
    5. </dependency>

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

    1. <!--配置SqlSessionFactory对象 -->
    2. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    3. <property name="dataSource" ref="dataSource" />
    4. <property name="configLocation" value="classpath:mybatis-config.xml" />
    5. <property name="typeAliasesPackage" value="com.aoChine.model.entity" />
    6. <property name="mapperLocations" value="classpath:mapper/*.xml" />
    7. <!-- 配置mybatis分页插件PageHelper -->
    8. <property name="plugins">
    9. <array>
    10. <bean class="com.github.pagehelper.PageInterceptor">
    11. <property name="properties">
    12. <!-- 什么都不配,使用默认的配置 -->
    13. <value></value>
    14. </property>
    15. </bean>
    16. </array>
    17. </property>
    18. </bean

    或者在mybatis配置文件中添加

    在mybatis-config.xml中定义

    1. <plugins>
    2. <!-- com.github.pagehelper为PageHelper类所在包名 -->
    3. <plugin interceptor="com.github.pagehelper.PageInterceptor">
    4. <!-- 使用MySQL方言的分页 -->
    5. <property name="helperDialect" value="oracle"/>
    6. <!--如果使用mysql,这里value为mysql-->
    7. <property name="pageSizeZero" value="true"/>
    8. </plugin>
    9. </plugins>

    代码实现:

    image.png