【ssm框架】使用PageHelper插件进行分页

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hemk340200600/article/details/78145496

通常我们要实现分页,都需要传入一个当前页,要读的数据个数,经过计算之后,将需要的值填入接在sql语句limit关键字的后面。然而使用PageHelper之后我们并不需要对sql添加什么limit,直接按查询全部去写sql语句即可。只要在查询之前调用PageHelper.startPage(page,rows),它会帮我们把limit及后面的内容自动注入到我们的sql语句中进行查询,大大方便了我们的开发以及sql语句的管理。下面就来看看如何使用这个插件吧。


一、首先在pom.xml添加依赖

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


二、在mybatis-config.xml中添加插件

<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <!-- 分页查询插件 -->
        <plugininterceptor="com.github.pagehelper.PageHelper">
            <propertyname="dialect" value="mysql" />
            <propertyname="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>


三、在spring-mybatis.xml中引入该配置文件

<bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
    <description>spring和MyBatis完美整合,不需要mybatis的配置映射文件</description>
    <propertyname="dataSource" ref="dataSource" />
    <propertyname="configLocation"value="classpath:mybatis/mybatis-config.xml" />
    <!-- 自动扫描mapping.xml文件 -->
    <propertyname="mapperLocations"value="classpath:mybatis/mappers/**/*.xml" />
</bean>
 

扫描二维码关注公众号,回复: 4727068 查看本文章

实际使用代码如下:

public PageInfo<User> listByPage(intpage, int rows, String keywords, UserType type) throws Exception{
    PageHelper.startPage(page,rows);
    List<User> list =userMapper.search(keywords, type, null);
    PageInfo<User> pageInfo = newPageInfo<>(list);
    return pageInfo;
}

 

猜你喜欢

转载自blog.csdn.net/Hemk340200600/article/details/78145496