1.首先导入分页插件的依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
2.配置分页拦截器插件
2.1. 在 MyBatis 配置 xml 中配置拦截器插件
<!--
plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下:
properties?, settings?,
typeAliases?, typeHandlers?,
objectFactory?,objectWrapperFactory?,
plugins?,
environments?, databaseIdProvider?, mappers?
-->
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name=" helperDialect" value="mysql"/>
</plugin>
</plugins>
2.2. 在 Spring 配置文件中配置拦截器插件
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
<!--配置mybatis分页插件-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--helperDialect:数据库类型-->
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
controller
package com.controller;
import com.entity.TCustomer;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.TCustomerService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.handler.HandlerResolver;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 客户controller
* @Auther lpl
* @Date 2020/3/15
*/
@Controller
@RequestMapping("/customer")
public class TCustomerController {
/**
* 注入TCustomerService
*/
@Autowired
private TCustomerService tcService;
private Map<String,Object> map = new HashMap<String,Object>();
/**
* 分页查询
* @param page 当前页
* @param rows 每页显示条数
* @return 返回客户集合
*/
@RequestMapping("/findPage")
@ResponseBody
public Map<String,Object> findPage(Integer page, Integer rows){
//设置分页参数
PageHelper.startPage(page,rows);
//查询所有
List<TCustomer> list = tcService.findAll();
//使用pageinfo封装数据
PageInfo<TCustomer> pageInfo = new PageInfo<TCustomer>(list);
//从pageinfo取出结果
//总记录数
long total = pageInfo.getTotal();
//当前页的数据
List<TCustomer> customerList = pageInfo.getList();
map.put("total",total);
map.put("rows",customerList);
return map;
}