pageHelper分页工具的使用
com.github.pagehelper
pagehelper
5.1.2
说明
@RequestMapping("/emps")
public String list(@RequestParam(required = false,defaultValue = "1",value = "pn")Integer pn,
Map map){
//引入分页查询,使用PageHelper分页功能
//在查询之前传入当前页,然后多少记录
PageHelper.startPage(pn,5);
//startPage后紧跟的这个查询就是分页查询
List emps = employeeService.getAll();
//使用PageInfo包装查询结果,只需要将pageInfo交给页面就可以
PageInfo pageInfo = new PageInfo(emps,5);
//pageINfo封装了分页的详细信息,也可以指定连续显示的页数
map.put("pageInfo",pageInfo);
return "list";
}
底层代码实现
@Override
public PageModel getList(ReceiveParameterModel receiveParameterModel) {
// TODO Auto-generated method stub
PageHelper.startPage(receiveParameterModel.getPage(), receiveParameterModel.getRows());
List query = receiveParameterModel.getQuery();
Map map = new HashMap();
for (JsonModel jsonModel : query) {
if (jsonModel.getValue() != null && jsonModel.getValue() != "") {
map.put(jsonModel.getName(), jsonModel.getValue());
}
}
return new PageModel(mapper.getList(map));
}
public interface InstallTrainService extends BaseService{
}
import com.cloud.core.model.PageModel;
import com.cloud.core.model.ReceiveParameterModel;
public interface BaseService{
/**
* 根据Id查询实体
* @param id
* @return
*/
T getById(Object id);
/**
* 根据条件查询
* @param receiveParameterModel
* @return
*/
PageModel getList(ReceiveParameterModel receiveParameterModel);
/**
* 插入实体
* @param entity
* @return
*/
T insert(T entity);
/**
* 更新实体
* @param entity
* @return
*/
T update(T entity);
/**
* 更新null值
* @param entity
* @return
*/
T updateNull(T entity) ;
void delete(List obj);
}
public class InstallTrainServiceImpl extends BaseServiceImpl implements InstallTrainService{
}
import com.cloud.core.model.PageModel;
import com.cloud.core.model.ReceiveParameterModel;
import com.cloud.core.service.BaseService;
import com.cloud.core.util.ExampleUtil;
import com.github.pagehelper.PageHelper;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import java.lang.reflect.ParameterizedType;
import java.util.List;
public class BaseServiceImpl implements BaseService {
@Autowired
protected M mapper;
public T getById(Object id) {
return mapper.selectByPrimaryKey(id);
}
public PageModel getList(ReceiveParameterModel receiveParameterModel) {
PageModel pageModel = null;
if (receiveParameterModel != null) {
Class clazz = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[1];
Example example = ExampleUtil.getExample(clazz, receiveParameterModel);
if (receiveParameterModel.getPage() == null || receiveParameterModel.getRows() == null) {
Integer total = mapper.selectCountByExample(example);
List list = mapper.selectByExample(example);
pageModel = new PageModel(total, list);
}
if (receiveParameterModel.getPage() != null && receiveParameterModel.getRows() != null) {
PageHelper.startPage(receiveParameterModel.getPage(), receiveParameterModel.getRows());
pageModel = new PageModel(mapper.selectByExample(example));
}
}
return pageModel;
}
public T insert(T entity) {
mapper.insert(entity);
return entity;
}
public T update(T entity) {
mapper.updateByPrimaryKeySelective(entity);
return entity;
}
public T updateNull(T entity) {
mapper.updateByPrimaryKey(entity);
return entity;
}
public void delete(List obj) {
obj.forEach(ob -> mapper.deleteByPrimaryKey(ob));
}
}
import com.github.pagehelper.PageInfo;
import java.util.List;
public class PageModel {
private Integer total;
private List rows;
public PageModel() {
}
public PageModel(Integer total, List rows) {
this.total = total;
this.rows = rows;
}
public PageModel(List list){
PageInfo pageInfo = new PageInfo(list);
Long tal = pageInfo.getTotal();
total= tal.intValue();
rows = pageInfo.getList();
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}
public class JsonModel {
private String name;
private String value;
private String type;
}
public class ReceiveParameterModel {
private Integer page;
private Integer rows;
private String sort;
private String order;
private List query;
private String querystr;
public List getQuery() {
if (query == null && querystr != null) {
try {
query = JSONArray.parseArray(querystr, JsonModel.class);
} catch (Exception e) {
throw new CntenException(query, "数据转换异常", e.getStackTrace().toString(), e);
}
}
return query;
}
}
import com.cloud.core.model.ReceiveParameterModel;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import tk.mybatis.mapper.entity.Example;
import java.util.Arrays;
import java.util.List;
public class ExampleUtil {
public static Example getExample(Class clazz, ReceiveParameterModel receiveParameterModel) {
Example example = example = new Example(clazz);
if (receiveParameterModel != null) {
List list = receiveParameterModel.getQuery();
String sort = receiveParameterModel.getSort();
String order = receiveParameterModel.getOrder();
Example.Criteria criteria = example.createCriteria();
if (list != null && list.size() > 0) {
for (JsonModel jsonModel : list) {
//实体类是否存在该字段且字段值不为空
if (jsonModel.getName() != null && jsonModel.getType() != null && StringUtil.isNotEmpty(jsonModel.getValue()) && existsField(clazz, jsonModel.getName())) {
if ("llike".equals(jsonModel.getType()) ) {
criteria.andLike(jsonModel.getName(), "%"+jsonModel.getValue());
continue;
}
if ("rlike".equals(jsonModel.getType()) ) {
criteria.andLike(jsonModel.getName(), jsonModel.getValue()+"%");
continue;
}
if ("like".equals(jsonModel.getType()) ) {
criteria.andLike(jsonModel.getName(), "%"+jsonModel.getValue()+"%");
continue;
}
if ("eq".equals(jsonModel.getType())) {
criteria.andEqualTo(jsonModel.getName(), jsonModel.getValue());
continue;
}
if ("lt".equals(jsonModel.getType())) {
criteria.andLessThan(jsonModel.getName(), jsonModel.getValue());
continue;
}
if ("le".equals(jsonModel.getType())) {
criteria.andLessThanOrEqualTo(jsonModel.getName(), jsonModel.getValue());
continue;
}
if ("gt".equals(jsonModel.getType())) {
criteria.andGreaterThan(jsonModel.getName(), jsonModel.getValue());
continue;
}
if ("ge".equals(jsonModel.getType())) {
criteria.andGreaterThanOrEqualTo(jsonModel.getName(), jsonModel.getValue());
continue;
}
if ("in".equals(jsonModel.getType())) {
criteria.andIn(jsonModel.getName(), getList(jsonModel.getValue()));
continue;
}
}
}
}
if (sort != null) {
if ("asc".equals(order)) {
example.orderBy(sort).asc();
}
if ("desc".equals(order)) {
example.orderBy(sort).desc();
}
}
}
return example;
}
/**
* 判断该实例是否存在该字段
* @param clz
* @param fieldName
* @return
*/
private static boolean existsField(Class clz,String fieldName){
try{
return clz.getDeclaredField(fieldName)!=null;
}
catch(Exception e){
}
if(clz!=Object.class){
return existsField(clz.getSuperclass(),fieldName);
}
return false;
}
/**
* 将字符串转换为集合
* @param string
* @return
*/
private static List getList(String string) {
String[] split = string.split(",");
List strings = Arrays.asList(split);
return strings;
}
}
layui的PageHelper
var url = CONTEXT_PATH + '/cusviews/rush/listRushRepair';
var showRushRepairList = new ShowRushRepairList("rushRepairList", "repairId", url);
showRushRepairList.render();
(function(scope){
var ListPager = Class.extend({
init: function(){},
render: function(){
var _self = this;
//弹出卡片界面的大小[60%,80%]
_self.cardSize = _self.cardSize || ['80%','80%'];
//弹出卡片界面方式:页面层(这里content是一个普通的String):1;iframe层(content是一个URl):2
_self.cardPopStyle = _self.cardPopStyle || LayuiPopStyle.LAYUI_IFRAME_LAYER;
_self.tableId = _self.container + "." + _self.primaryKey;
//plugins 这个可以不传,但是请不要传空数组过来
var plugins = _self.plugins || ['table','form'];
var p = _self.assemblyFormPrams();
//利用layui 绘制列表 ( url : _self.url+"?decAjaxReq=yes", 给ajax请求加密)
debugger;
layui.use(plugins, function(){
var option = $.extend({elem: "#" + _self.container,
url : _self.url,
cols: _self.title,
method: RequestMethod.METHOD_POST,
id : _self.tableId,
even: true,
page: true, //是否显示分页
pageNum: 1,
limit: _self.pageSize, //每页默认显示的数量
limits:[5,10,15,20,30],
done:function(res, curr, count){
if(_self.afterDone && $.isFunction(_self.afterDone)){
_self.afterDone(res, curr, count);
}
}}, _self.layOption);
//展示已知数据
layui.table.render(option);
//渲染部分layui组件
_self.initLayuiPlugin();
//监听工具条
layui.table.on('tool(' + _self.container + ')', function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
if(_self.hookMethod && $.isFunction(_self.hookMethod)){
_self.hookMethod(obj); //回调 子类中的 钩子方法
}
});
//复选框事件选中以后回调
layui.table.on('checkbox(' + _self.container + ')', function(obj){
if(_self.tableAfterChecked && $.isFunction(_self.tableAfterChecked)){
_self.tableAfterChecked(obj); //回调 子类中的 钩子方法
}
});
});
//界面绘制完成, 初始化界面事件
_self.initEvent();
},
initLayuiPlugin: function(){
var _self = this;
},
initEvent: function(){
var _self = this;
//列表 增删改查
$("div[name='listBtns'] button").unbind('click').bind('click', function(){
var action = "_self." + $(this).attr("action");
eval(action);
});
//列表查询、重置
$("div button[type='button']",$("#" + _self.container + "-QueryForm"))
.unbind('click')
.bind('click', function(){
var action = "_self." + $(this).attr("action");
eval(action);
});
//二级页面查询a标签
$("div a[id='search']",$("#" + _self.container + "-QueryForm"))
.unbind('click')
.bind('click', function(){
var action = "_self." + $(this).attr("action");
eval(action);
});
},
assemblyFormPrams: function(){
//组装列表模糊查询表单数据
var _self = this;
var formParam = $("#" + _self.container + "-QueryForm").serializeArray(),
reqParam = {};
for(var o in formParam){
if(formParam[o]["name"]){
reqParam[formParam[o]["name"]] = formParam[o]["value"];
}
}
return reqParam;
},
listQuery: function(){
var _self = this;
layui.table.reload(_self.tableId, {
where: _self.assemblyFormPrams()
});
}
});
scope.ListPager = ListPager;
})(window);
public LayPage getRushRepairList(int page, int limit,RushRepairVO vo)
{
PageHelper.startPage(page, limit);
List list = rushMapper.getRushRepairList(vo);
return new LayPage(list);
}
import com.github.pagehelper.Page;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
public class LayPage
implements Serializable
{
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private int pageNum;
private int pageSize;
private int count;
private int startRow;
private int endRow;
private long total;
private int pages;
private List data;
private int prePage;
private int nextPage;
private boolean isFirstPage = false;
private boolean isLastPage = false;
private boolean hasPreviousPage = false;
private boolean hasNextPage = false;
private int navigatePages;
private int[] navigatepageNums;
private int navigateFirstPage;
private int navigateLastPage;
public LayPage() {}
public LayPage(List list)
{
this(list, 8);
}
public LayPage(List list, int navigatePages)
{
if ((list instanceof Page))
{
Page page = (Page)list;
this.pageNum = page.getPageNum();
this.pageSize = page.getPageSize();
this.code = 0;
this.msg = "";
this.pages = page.getPages();
this.data = page;
this.count = ((int)page.getTotal());
this.total = page.getTotal();
if (this.count == 0)
{
this.startRow = 0;
this.endRow = 0;
}
else
{
this.startRow = (page.getStartRow() + 1);
this.endRow = (this.startRow - 1 + this.count);
}
}
else if ((list instanceof Collection))
{
this.pageNum = 1;
this.pageSize = list.size();
this.pages = (this.pageSize > 0 ? 1 : 0);
this.data = list;
this.count = list.size();
this.total = list.size();
this.startRow = 0;
this.endRow = (list.size() > 0 ? list.size() - 1 : 0);
}
if ((list instanceof Collection))
{
this.navigatePages = navigatePages;
calcNavigatepageNums();
calcPage();
judgePageBoudary();
}
}
private void calcNavigatepageNums()
{
if (this.pages this.pages)
{
endNum = this.pages;
for (int i = this.navigatePages - 1; i >= 0; i--) {
this.navigatepageNums[i] = (endNum--);
}
}
else
{
for (int i = 0; i < this.navigatePages; i++) {
this.navigatepageNums[i] = (startNum++);
}
}
}
}
private void calcPage()
{
if ((this.navigatepageNums != null) && (this.navigatepageNums.length > 0))
{
this.navigateFirstPage = this.navigatepageNums[0];
this.navigateLastPage = this.navigatepageNums[(this.navigatepageNums.length - 1)];
if (this.pageNum > 1) {
this.prePage = (this.pageNum - 1);
}
if (this.pageNum < this.pages) {
this.nextPage = (this.pageNum + 1);
}
}
}
private void judgePageBoudary()
{
this.isFirstPage = (this.pageNum == 1);
this.isLastPage = ((this.pageNum == this.pages) || (this.pages == 0));
this.hasPreviousPage = (this.pageNum > 1);
this.hasNextPage = (this.pageNum < this.pages);
}
public int getPageNum()
{
return this.pageNum;
}
public void setPageNum(int pageNum)
{
this.pageNum = pageNum;
}
public int getPageSize()
{
return this.pageSize;
}
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}
public int getCount()
{
return this.count;
}
public void setCount(int count)
{
this.count = count;
}
public int getStartRow()
{
return this.startRow;
}
public void setStartRow(int startRow)
{
this.startRow = startRow;
}
public int getEndRow()
{
return this.endRow;
}
public void setEndRow(int endRow)
{
this.endRow = endRow;
}
public long getTotal()
{
return this.total;
}
public void setTotal(long total)
{
this.total = total;
}
public int getPages()
{
return this.pages;
}
public void setPages(int pages)
{
this.pages = pages;
}
public List getData()
{
return this.data;
}
public void setData(List data)
{
this.data = data;
}
@Deprecated
public int getFirstPage()
{
return this.navigateFirstPage;
}
@Deprecated
public void setFirstPage(int firstPage)
{
this.navigateFirstPage = firstPage;
}
public int getPrePage()
{
return this.prePage;
}
public void setPrePage(int prePage)
{
this.prePage = prePage;
}
public int getNextPage()
{
return this.nextPage;
}
public void setNextPage(int nextPage)
{
this.nextPage = nextPage;
}
@Deprecated
public int getLastPage()
{
return this.navigateLastPage;
}
@Deprecated
public void setLastPage(int lastPage)
{
this.navigateLastPage = lastPage;
}
public boolean isIsFirstPage()
{
return this.isFirstPage;
}
public void setIsFirstPage(boolean isFirstPage)
{
this.isFirstPage = isFirstPage;
}
public boolean isIsLastPage()
{
return this.isLastPage;
}
public void setIsLastPage(boolean isLastPage)
{
this.isLastPage = isLastPage;
}
public boolean isHasPreviousPage()
{
return this.hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage)
{
this.hasPreviousPage = hasPreviousPage;
}
public boolean isHasNextPage()
{
return this.hasNextPage;
}
public void setHasNextPage(boolean hasNextPage)
{
this.hasNextPage = hasNextPage;
}
public int getNavigatePages()
{
return this.navigatePages;
}
public void setNavigatePages(int navigatePages)
{
this.navigatePages = navigatePages;
}
public int[] getNavigatepageNums()
{
return this.navigatepageNums;
}
public void setNavigatepageNums(int[] navigatepageNums)
{
this.navigatepageNums = navigatepageNums;
}
public int getNavigateFirstPage()
{
return this.navigateFirstPage;
}
public int getNavigateLastPage()
{
return this.navigateLastPage;
}
public void setNavigateFirstPage(int navigateFirstPage)
{
this.navigateFirstPage = navigateFirstPage;
}
public void setNavigateLastPage(int navigateLastPage)
{
this.navigateLastPage = navigateLastPage;
}
public int getCode()
{
return this.code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMsg()
{
return this.msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public String toString()
{
StringBuffer sb = new StringBuffer("PageInfo{");
sb.append("pageNum=").append(this.pageNum);
sb.append(", pageSize=").append(this.pageSize);
sb.append(", count=").append(this.count);
sb.append(", startRow=").append(this.startRow);
sb.append(", endRow=").append(this.endRow);
sb.append(", total=").append(this.total);
sb.append(", pages=").append(this.pages);
sb.append(", data=").append(this.data);
sb.append(", prePage=").append(this.prePage);
sb.append(", nextPage=").append(this.nextPage);
sb.append(", isFirstPage=").append(this.isFirstPage);
sb.append(", isLastPage=").append(this.isLastPage);
sb.append(", hasPreviousPage=").append(this.hasPreviousPage);
sb.append(", hasNextPage=").append(this.hasNextPage);
sb.append(", navigatePages=").append(this.navigatePages);
sb.append(", navigateFirstPage=").append(this.navigateFirstPage);
sb.append(", navigateLastPage=").append(this.navigateLastPage);
sb.append(", navigatepageNums=");
if (this.navigatepageNums == null)
{
sb.append("null");
}
else
{
sb.append('[');
for (int i = 0; i < this.navigatepageNums.length; i++) {
sb.append(i == 0 ? "" : ", ").append(this.navigatepageNums[i]);
}
sb.append(']');
}
sb.append('}');
return sb.toString();
}
}