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变量, 使用 ...
随机推荐
- Net使用RdKafka引发异常RdKafka.Internal.LibRdKafka 的类型初始值设定项引发异常
在Net中VS2015用RdKafka组件开发消息发布和消费,引发下面的异常 RdKafka.Internal.LibRdKafka 的类型初始值设定项引发异常System.TypeInitializ ...
- 向上造型中让我入坑的地方 (><)
今天周六,闲着蛋疼就报名参加了公司的一个java比赛,比赛地点某某大厦11楼会议室,想象中应该是能容纳上百人的超大会议室.没成想,到地方一看,只是一个能容纳六七人的有圆形会议桌的小会议室.不过这仍然不 ...
- Python机器学习笔记:XgBoost算法
前言 1,Xgboost简介 Xgboost是Boosting算法的其中一种,Boosting算法的思想是将许多弱分类器集成在一起,形成一个强分类器.因为Xgboost是一种提升树模型,所以它是将许多 ...
- go基础系列:简介
1.Go简介 Go语言是编译型.静态类型的类C的语言,并带有GC(垃圾收集器,garbage collection).这意味着什么? 另外,Go是一种非常严格的语言,它几乎总是要求我们"以标 ...
- 业务开发(八)—— Maven
0x01.maven install成功后,项目旁边依然有个红叉 maven--update--选中下方Force Update of Snapsshots/Releases 0x02.An inte ...
- 一个word文档中,多个表格的批量调整(根据窗口调整表格和添加表格水平线)
Sub 自动调整所有表格() ' ' 自动调整所有表格 宏 ' 'Application.Browser.Target = wdBrowseTable For i = 1 To ActiveDocum ...
- [转]nodeJS中redis初步使用
本文转自:https://blog.csdn.net/frankenjoy123/article/details/55209637 Node.js下使用Redis,首先: 1.有一台安装了Redis的 ...
- SQL 注入漏洞
首先要知道sql注入形成的原因:用户输入的数据被sql解释器执行 sql注入又分:数字型,字符型,cookie 注入,post注入,延时注入,搜索注入,base64注入 如何甄别一个模块是否有sql注 ...
- XAML: 在 MVVM 模式中,关于绑定的几处技巧
以下会提到三个绑定的技巧,分别是 在 ListView 中为 ListViewItem 的 MenuFlyout 绑定 Command: 在 ListView 的 事件中绑定所选择项目,即其 Sele ...
- [android] 获取系统的联系人信息
内容提供是实质上是个接口,后门,他给别人提供数据,系统联系人是个比较复杂的内容通过者. 找到/data/data/com.android.providers.contacts/contacts2.db ...