参考博主:https://blog.csdn.net/liuyi6/article/details/82505056
1.插件依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2.插件配置(在spring-dao.xml文件的SqlSessionFactory的bean中添加)
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
<!-- helperDialect:有别于3.0+版本,现在必须是helperDialect,否则spring启动加载时会报错 -->
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
3.service层添加分页查询接口:
public interface ProductService {
List<Product> findAllProductByPage(int pageNum, int pageSize);//分页查询
}
4.serviceImp层实现分页方法:
@Service
public class ProductServiceImp implements ProductService {
@Autowired
ProductMapper productMapper;
/**
* 分页查询
* pageNum 开始页数
* pageSize 每页显示的数据条数
*/
@Override
public List<Product> findAllProductByPage(int pageNum, int pageSize) {
//将参数传给方法实现分页
PageHelper.startPage(pageNum, pageSize);
ProductExample example = new ProductExample();
List<Product> list = productMapper.selectByExample(example);
return list;
}
}
5.测试分页的参数:
public class ProductServiceImpTest extends BaseTest {
@Autowired
ProductMapper productMapper;
@Autowired
ProductService productService;
@Test
public void findAllProduct() {
int pageNum = 1;//第几页
int pageSize = 2;//每页显示的数据条数
List<Product> list = productService.findAllProductByPage(pageNum , pageSize);
//获取分页信息
PageInfo<Product> pageInfo = new PageInfo<Product>(list);
System.out.println(list.toString());
System.out.println("total:" + pageInfo.getTotal());//数据总条数
System.out.println("pages:" + pageInfo.getPages());//数据总页数
System.out.println("pageSize:" + pageInfo.getPageSize());//每页显示条数
}
}