java使用插件pagehelper在mybatis中实现分页查询

时间:2024-01-20 09:11:27

摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件

PageHelper是国内牛人的一个开源项目,有兴趣的可以去看源码,都有中文注释

开源项目地址: https://pagehelper.github.io/

请求URL:http://localhost:8080/listCity?page=1&limit=10

显示数据:

java使用插件pagehelper在mybatis中实现分页查询

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&amp;useUnicode=true&amp;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中实现分页查询