//当前页的页码pageNum pageNumprivate int pageNum;//当前页大小pageSize pageSizeprivate int pageSize;//总数据个数totalSize totalsizeprivate long totalSize;//总页数pageCount page Countprivate int pageCount;//当前页数据List<T> data List<T> dataprivate List<T> data;//----------pagebean的5个基本属性//----------给此类添加构造方法和getter,setterpublicPageBean(){}publicPageBean(int pageNum, int pageSize, long totalSize, List<T> data){this.pageNum = pageNum;this.pageSize = pageSize;this.totalSize = totalSize;this.data = data;
pageCount=(int)(totalSize%pageSize==0?totalSize/pageSize:totalSize/pageSize+1);//注意此处总页数不变的所以直接计算}public int getPageNum(){return pageNum;}publicvoidsetPageNum(int pageNum){this.pageNum = pageNum;}public int getPageSize(){return pageSize;}publicvoidsetPageSize(int pageSize){this.pageSize = pageSize;}public long getTotalSize(){return totalSize;}publicvoidsetTotalSize(long totalSize){this.totalSize = totalSize;}public int getPageCount(){return pageCount;}publicvoidsetPageCount(int pageCount){this.pageCount = pageCount;}public List<T>getData(){return data;}publicvoidsetData(List<T> data){this.data = data;}
在dao层中添加查找方法并实现:
//----------在接口中的方法
User finbyid(int id);
List<User>findByPage(int pageNum,int pageSize);
long getCount();//----------实现
@Override
public User finbyid(int id){
QueryRunner qr =newQueryRunner(DataSourceUtils.getDataSource());try{return qr.query("select * from empno where id=? ",newBeanHandler<User>(User.class),id);}catch(SQLException e){
e.printStackTrace();thrownewRuntimeException("按照id查找失败");}}
@Override
public List<User>findByPage(int pageNum, int pageSize){
QueryRunner qr =newQueryRunner(DataSourceUtils.getDataSource());try{return qr.query("select * from empno order by id limit ?,?",newBeanListHandler<User>(User.class),(pageNum-1)*pageSize,pageSize);}catch(SQLException e){
e.printStackTrace();thrownewRuntimeException("分页查询失败");}}
@Override
public long getCount(){
QueryRunner qr =newQueryRunner(DataSourceUtils.getDataSource());try{return qr.query("select count(*) from empno",newScalarHandler<>());}catch(SQLException e){
e.printStackTrace();thrownewRuntimeException("查询分页时个数失败");}}
在service层包装:
//-----------在接口中的方法
PageBean<User>findPage(int pageNum,int pageSize);
User queryByid(int id);//-----------实现
@Override
public PageBean<User>findPage(int pageNum, int pageSize){
List<User> data = userDao.findByPage(pageNum, pageSize);
long totalSize = userDao.getCount();
PageBean<User> pageBean =newPageBean<>(pageNum, pageSize, totalSize, data);return pageBean;}
@Override
public User queryByid(int id){return userDao.finbyid(id);}