自定义分页得业务需求在哪都存在,一般常用的是PageHelper插件,今天给大家提供一个自定义的PageHelper类。
一.mybatis-mapper.xml配置
<choose>
<when test="sidx != null and sidx.trim() != ''">
order by ${sidx} ${order}
</when>
<otherwise>
order by trackId
</otherwise>
</choose>
<if test="offset != null and pageSize != null">
limit #{offset}, #{pageSize}
</if>
二.java代码
public class Query extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;
// 当前页码
private int pageNo;
// 每页条数
private int pageSize;
public Query(JSONObject params) {
this.putAll(params);
int pageNo = (params == null || params.getInteger("pageNo") == null) ? 1 : params.getInteger("pageNo");
int pageSize = (params == null || params.getInteger("pageSize") == null) ? 10 : params.getInteger("pageSize");
this.pageNo = pageNo;
this.pageSize = pageSize;
// 分页参数
this.put("offset", (pageNo - 1) * pageSize);
this.put("pageNo", pageNo);
this.put("pageSize", pageSize);
// 防止SQL注入(因为sidx、order是通过拼接SQL实现排序的,会有SQL注入风险)
if(params.containsKey("sidx")) {
String sidx = params.get("sidx").toString();
this.put("sidx", SQLFilter.sqlInject(sidx));
}else {
this.put("sidx", "");
}
if(params.containsKey("order")) {
String order = params.get("order").toString();
this.put("order", SQLFilter.sqlInject(order));
}else {
this.put("order", "");
}
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}