以下code就不一一解释了,看不懂的伙伴留言咨询,文末给一个总页数计算的页面
VO:
public class PageBean<T> { // 1.当前页数 从页面获取 private int currentPage; // 2.每页显示数据个数,赋初值或者setter获取 private int currentCount; // 3.总条数,从数据库获取 private int totalRecord; // 4.总页数,计算得到 private int totalPage; // 5.每页的显示数据,数据库得到 List<T> list = new ArrayList<>(); //getter/setter }
public class SearchRequest { private Integer From; private Integer pageSize; // .....其他查询条件 private String id; private String beginTime; private String endTime; //getter/setter }
Servicice:
public PageBean<User> getRecord(SearchRequest searchRequest, PageBean<User> pageBean)throws Exception;
ServiceImpl:
public PageBean<User> getRecord(SearchRequest searchRequest,PageBean<User> pageBean) throws Exception{ //当前页面,数据库进行分页的方法searchrequest加入from 和to int currentPage=pageBean.getCurrentPage(); //页面的显示个数 int currentCount=pageBean.getCurrentCount(); //根据页面算出数据库查询的起始位置 int from=currentCount*(currentPage-1); //获取的数据个数 int pageSize=currentCount; pageBean.setTotalRecord((int) dao.findForObject("Mapper.findCount",null)); //计算总页数公式//总记录数除以每页数据条数+总记录数取余每页数据条数大于o,结果为1.不大于结果为0; int total=pageBean.getTotalRecord()/currentCount+(pageBean.getTotalRecord()%currentCount>0?1:0); pageBean.setTotalPage(total); //将查询范围在查询条件里 searchRequest.setFrom(from); searchRequest.setPageSize(pageSize); //根据以上条件返回目的对象 List<User> userList; try { userList = (List<User>) dao.findForList("Mapper.getRepairRecord", searchRequest); pageBean.setList(userList); } catch (Exception e) { e.printStackTrace(); return null; } return pageBean; }
Mapper:
<!-- 查询表总条数 --> <select id="findCount" resultType="Integer"> select COUNT(id) as id from <include refid="tableName"></include> </select>
//查询分页数据 <select id="getRepairRecord" resultMap="ResultMap" parameterType="SearchRequest"> select <include refid="Field"></include> from <include refid="tableName"></include> where ms_id = #{id} <if test="beginTime!=null and beginTime!=''"> AND produce_time >=#{beginTime} </if> <if test="endTime!=null and endTime!=''"> AND produce_time <=#{endTime} </if> ORDER BY time DESC <if test="From!=null and pageSize!=null"> LIMIT #{From},#{pageSize} </if> </select>
Controller:
public JSONObject productDataList(String productData,String pageBeanJson) throws Exception { //其他字段赋值/....... /....... PageBean<User> userList = Service.getRecord(searchRequest,pageBean); /............. }