java使用插件pagehelper在mybatis中实现分页查询
摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件
PageHelper是国内牛人的一个开源项目,有兴趣的可以去看源码,都有中文注释
开源项目地址: https://pagehelper.github.io/
请求URL:http://localhost:8080/listCity?page=1&limit=10
显示数据:

1、PageHelper的maven依赖及插件配置
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.6</version>
</dependency>
PageHelper除了本身的jar包外,它还依赖了一个叫jsqlparser的jar包,使用时,我们不需要单独指定jsqlparser的maven依赖,maven的间接依赖会帮我们引入。
2、配置拦截器插件
这个是配置在mybatis-config.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="param1" value="value1"/>
</plugin>
</plugins>
3、我的配置mybatis-config.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<typeAliases>
<package name="edu.nf.entity"/>
</typeAliases>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--helperDialect 方言:就表示此插件针对哪个数据库进行优化处理
这个方言可以不配置,因为此插件可以依据你的 url 的信息来推断出
你用的数据库是哪一个
-->
<property name="helperDialect" value="mysql"/>
<!--分页合理化参数-->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
<!--配置数据库-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/citydb?useSSL=true&useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="mapper/city-mapper.xml"/>
</mappers>
</configuration>
4、city-mapper.xml 数据库查询语句配置:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.nf.dao.CityDao">
<resultMap id="cityMap" type="city" >
<id property="cityId" column="city_id"/>
<result property="cityEn" column="city_en"/>
<result property="cityCn" column="city_cn"/>
<result property="countryCode" column="country_code"/>
<result property="countryEn" column="country_en"/>
<result property="countryCn" column="country_cn"/>
<result property="provinceEn" column="province_en"/>
<result property="provinceCn" column="province_cn"/>
</resultMap>
<!-- 这里写查询全部数据,配置好的分页插件他会自己加上limit 查询语句后面不能加; -->
<select id="listCity" resultMap="cityMap">
select * from city_test
</select>
<delete id="deleteCity" parameterType="java.util.List">
delete from city_test where city_id in
<foreach collection="list" item="city" open="(" separator="," close=")">
#{city.cityId}
</foreach>
</delete>
</mapper>
5、后台分页查询 servlet:
/**
* @author hh
* @Date 2018/9/15
*/
@WebServlet("/listCity")
public class CityListServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json;charset=utf-8");
//取出前端请求参数
String page=req.getParameter("page");
String limit=req.getParameter("limit"); //分页查询结果 page页数 limit显示行数
List<City> listCity=new CityService().listCity(page,limit); // 包装Page对象 listCity:page结果 , navigatePages: 页码数量
PageInfo<City> list=new PageInfo<>(listCity,1); //自己写的一个响应视图类,因为前端用的是layui框架需要自己,所以自己定义ResponseView
ResponseView vo=new ResponseView();
//设值 取出总数据行
vo.setCount(list.getTotal());
//设值 查询的结果
vo.setData(list.getList());
//响应前端
resp.getWriter().print(new Gson().toJson(vo));
}
}
6、响应视图类 ResponseView (因为前端用的是layui框架需要自己,所以自己定义ResponseView):
package edu.nf.vo; /**
* @author hh
* @Date 2018/9/15
*/
public class ResponseView {
private int code =0;
private Long count=0L;
private Object data; public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public Long getCount() {
return count;
} public void setCount(Long count) {
this.count = count;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
}
}
7、实体类 City:
package edu.nf.entity; /**
* @author hh
* @Date 2018/9/14
*/
public class City {
private String cityId;
private String cityEn;
private String cityCn;
private String countryCode;
private String countryEn;
private String countryCn;
private String provinceEn;
private String provinceCn; public String getCityId() {
return cityId;
} public void setCityId(String cityId) {
this.cityId = cityId;
} public String getCityEn() {
return cityEn;
} public void setCityEn(String cityEn) {
this.cityEn = cityEn;
} public String getCityCn() {
return cityCn;
} public void setCityCn(String cityCn) {
this.cityCn = cityCn;
} public String getCountryCode() {
return countryCode;
} public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
} public String getCountryEn() {
return countryEn;
} public void setCountryEn(String countryEn) {
this.countryEn = countryEn;
} public String getCountryCn() {
return countryCn;
} public void setCountryCn(String countryCn) {
this.countryCn = countryCn;
} public String getProvinceEn() {
return provinceEn;
} public void setProvinceEn(String provinceEn) {
this.provinceEn = provinceEn;
} public String getProvinceCn() {
return provinceCn;
} public void setProvinceCn(String provinceCn) {
this.provinceCn = provinceCn;
}
}
8、service 逻辑业务层(CityService):
/**
* @author hh
* @Date 2018/9/15
*/
public class CityService {
/**
* 分页查询 城市信息集合
* @return
*/
public List<City> listCity(String offest,String pageSize){
//类型转换
Integer pnum=Integer.valueOf(offest);
Integer psize=Integer.valueOf(pageSize);
//调用PageHelper获取第1页,10条内容,默认查询总数count
PageHelper.startPage(pnum,psize);
//调用CityDaoImpl 分页查询
return new CityDaoImpl().listCity();
} /**
* 批量删除
* @param cityData
* @return
*/
public int deleteCity(String cityData){
List<City> list=new Gson().fromJson(cityData,new TypeToken<List<City>>(){}.getType());
try {
new CityDaoImpl().deleteCity(list);
return 200;
} catch (Exception e) {
e.printStackTrace();
return 403;
}
}
}
9、Dao 接口类:
/**
* @author hh
* @Date 2018/9/14
*/
public interface CityDao {
/**
* 城市信息列表
* @return
*/
List<City> listCity(); /**
* 批量删除
* @param listCity
*/
void deleteCity(List<City> listCity);
}
10、Dao实现类:
/**
* @author hh
* @Date 2018/9/14
*/
public class CityDaoImpl implements CityDao {
@Override
public List<City> listCity() {
List<City> list=null;
try(SqlSession sqlSession = MybatisUtil.getSqlSession()){
CityDao cityDao=sqlSession.getMapper(CityDao.class);
list=cityDao.listCity();
}
return list;
} @Override
public void deleteCity(List<City> listCity) {
try(SqlSession sqlSession = MybatisUtil.getSqlSession()){
CityDao cityDao=sqlSession.getMapper(CityDao.class);
cityDao.deleteCity(listCity);
}
}
}
我的项目案例(包括了上一篇博客的分页查询):点我下载
项目结构:

java使用插件pagehelper在mybatis中实现分页查询的更多相关文章
- mybatis中的高级查询
Mybatis作为一个ORM框架,肯定是支持sql高级查询的. 下面的一个案例来为大家详细讲解mybatis中的高级查询. 案例说明: 此案例的业务关系是用户,订单,订单详情与商品之间的关系. 以订单 ...
- 如何用Mybatis逆向工程实现分页查询(更改生成的Example)
如何用Mybatis逆向工程实现分页查询 一个很简单的方法,如果要mysql实现分页查询的话,执行下述语句即可 select * from table limit (offset)5,(limit) ...
- ssh框架中的分页查询
ssh中的分页查询是比较常用的,接下来我用代码来介绍如何实现一个分页查询 首先建立一个Model用来储存查询分页的信息 package com.haiziwang.qrlogin.utils; imp ...
- mongo中的分页查询
/** * @param $uid * @param $app_id * @param $start_time * @param $end_time * @param $start_page * @p ...
- PageHelper在Mybatis中的使用
环境:Spring 4.2.1 Mybatis 3.2.8 pagehelper 5.1.2 Mybatis官方教程:https://github.com/pagehelper/Mybatis-Pag ...
- Mybatis中的in查询和foreach标签
Mybatis中的foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合. foreach元素的属性主要有 item,index,collection,open,separato ...
- SSM-MyBatis-13:Mybatis中多条件查询
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 实体类 public class Book { private Integer bookID; private ...
- 【mybatis】mybatis中放置IN查询拼接sql过长,IN查询进行分批次查询的处理
需要使用的切割list集合的工具类,链接:https://www.cnblogs.com/sxdcgaq8080/p/9376947.html 处理逻辑,原本的一个LIst,进行切割,循环进行myba ...
- mybatis中Oracle分页语句的写法
最近一段时间使用oracle数据库查询分页, 用的是springboot. Oracle数据库中没有像mysql中limit的写法, 只能换其他方式写. 考虑到oracle中的ROWNUM变量, 使用 ...
随机推荐
- Java并发编程之AQS
一.什么是AQS AQS(AbstractQueuedSynchronize:队列同步器)是用来构建锁或者其他同步组件的基础框架,很多同步类都是在它的基础上实现的,比如常用的ReentrantLock ...
- Docker 快速入门之 Dockerfile
在 Docker 中我们可以从名为 Dockerfile 的文件中读取指令并且自动构建镜像.在本文中,将介绍 Dockerfile 的基本语法以及基本知识. Dockerfile 是什么 Docker ...
- 正确重写hashcode hashcode与equals方法 集合元素如何判断是否相等 集合如何查看是否包含某个元素
首先记住两句话 相等的两个对象,即equals(Object)方法判断两个对象相等,那么他们必须要有相同的hashcode hashcode相同的两个对象,他们可能相同,也可能不相同 简单地说可以这么 ...
- Java——代码块
前言 在程序编写之中可以直接使用{...}定义的一段语句就是代码块.根据代码块的位置以及关键字的不同可以分为4种:普通代码块.构造块.静态块以及同步代码块(多线程相关).下面将先介绍前3种以及Java ...
- python面向对象入门(1):从代码复用开始
本文从代码复用的角度一步一步演示如何从python普通代码进化到面向对象,并通过代码去解释一些面向对象的理论.所以,本文前面的内容都是非面向对象的语法实现方式,只有在最结尾才给出了面向对象的简单语法介 ...
- MONGODB(二)——索引操作
一.1.插入10w条数据> for(var i = 0;i<100000;i++){... var rand = parseInt(i*Math.random());... db.pers ...
- Javascript 定时器调用传递参数的方法
文章来源: https://m.jb51.net/article/20880.htm 备注:先记下,以后整理: Javascript 定时器调用传递参数的方法,需要的朋友可以参考下. 无论是wind ...
- Linux CentOS 虚拟机下联网
这里用VM 提供虚拟环境 虚拟机网络连接模式用的NAT 在编辑处 打开 查看你的子网ip 类型是NAT 的 我们这是是18 192.168.18.~ 去看dhcp 设置看自动分配的地址范围 也可 ...
- python基础学习(九)字典
字典的定义 dictionary(字典) 是 除列表以外 Python 之中 最灵活 的数据类型(有点类似java中的Map) 字典同样可以用来 存储多个数据 通常用于存储 描述一个 物体 的相关信息 ...
- 异常: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configurat
异常: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. ...