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]类初始化挺有意思的题目
public class Base { private String baseName = "base"; public Base() { callName(); } public ...
- JwtBearer认证
ASP.NET Core 认证与授权[4]:JwtBearer认证 在现代Web应用程序中,通常会使用Web, WebApp, NativeApp等多种呈现方式,而后端也由以前的Razor渲染HT ...
- linux 命令 — cut
cut 以列的方式格式化输出 依赖定界符 cut -f field_list filename 以默认定界符(tab,制表符)分割文件的列,输出指定的列field_list,field_list由列号 ...
- MFC应用技术之CTreeControl的使用
MFC应用技术之CTreeControl的使用 一丶MFC添加树控件.添加父节点跟子节点. MFC上面放一个树控件.并未这个树控件绑定变量.然后添加一个按钮.按钮的作用就是添加父节点跟子节点. PS: ...
- Magicodes.NET框架之路——让代码再飞一会(ASP.NET Scaffolding)
首先感谢大家对Magicodes.NET框架的支持.就如我上篇所说,框架成熟可能至少还需要一年,毕竟个人力量实在有限.希望有兴趣的小伙伴能够加入我们并且给予贡献.同时有问题的小伙伴请不要在群里询问问题 ...
- mysql列反转Pivoting
Pivoting是一项可以把行旋转为列的技术.在执行Pivoting的过程中可能会使用到聚合.Pivoting技术应用非常广泛.下面讨论的都是静态的Pivoting查询,即用户需要提前知道旋转的属性和 ...
- eclipse中使用pull报错(git提交冲突)
1.工程->Team->pull:报错 解决方案: 2.工程->Team->Syschronize Workspace: 3.在左侧会将有冲突的代码列举出来:(可选操作:在其上 ...
- 解决QTableWidget不显示数据的问题
QTableWidget通常用于数据的展示,通过其表格布局可以让用户更清晰的查看数据,同时也让数据的筛选变得更加直观. 不过,初学者们和粗心大意的人总是会发现明明自己数据已经正常添加,可是程序运行之后 ...
- JS脚本获取URL参数并调用
首先增加一个脚本库,可以是Zepto或者jQuery的,然后获取之后使用switch进行分流处理 <script type="text/javascript" src=&qu ...
- WPF 绕圈进度条(一)
在设计界面时,有时会遇到进度条,本次讲解如何设计自定义的绕圈进度条,直接上代码: 1.控件界面 <UserControl x:Class="ProgressBarControl&quo ...