分页查询

分页查询:

将所需数据建立一个实体类PageBean

需要获取当前页的值,并转为int类型

String currentPageStr=request.getParameter("currentPage");
Integer currentPage=Integer.parseInt(currentPageStr);

获取每页显示的条数,或手动设置

Integer currentCount=12;
//Integer currentCount=request.getParameter("");

调用service层方法

PageBean<Product> page=productService.getPage(currentPage,currentCount);

Service:

PageBean<Product> page=new PageBean<Product>();
        //目的:封装一个PageBean返回给客户端
        //封装当前页
        page.setCurrentPage(currentPage);
        //每页条数
        page.setCurrentCount(currentCount);
        //封装总条数,count(*)
        int totalCount=0;
        try {
            totalCount=productDao.getTotalCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        page.setTotalCount(totalCount);
        //总页数: 总条数/每页显示条数, *1.0向上取整
        int totalPage=(int) Math.ceil(totalCount*1.0/currentCount);
        page.setTotalPage(totalPage);
        //每页显示的条数
        // 起始页=(当前页-1)*每页显示条数
        // 1,0,12        2,12,12          3,24,12       S=(n-1)*a
        //计算起始页的索引
        int index=(currentPage-1)*currentCount;
        List<Product> list=null;
        //根据索引取值
        try {
            list=productDao.getProductByPage(index, currentCount);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        page.setList(list);
        return page;
        }

Dao层: select * from product limit ?,?

 条件查询:

QueryRunner qr=new QueryRunner(MyDBUtils.getDataSource());
        String sql="select * from product where 1=1 "; 
        ArrayList<String> list=new ArrayList<String>();
        //拼串
        if (condition.getPname()!=null&&condition.getPname().trim()!=""){//先判断不为空,再判断是否为空串
            sql+=" and pname like ?";
            list.add("%"+condition.getPname()+"%"); //添加进集合
        }
        if(condition.getCid()!=null &&condition.getCid()!=""){
            sql+=" and cid=?";
            list.add(condition.getCid());
        }
        if(condition.getIs_hot()!=null&& condition.getIs_hot()!=""){
            sql+=" and is_hot=?";
            list.add(condition.getIs_hot());
        }
        List<Product> arr=qr.query(sql, new BeanListHandler<Product>(Product.class),
                list.toArray());   //toArray()可为空
        return arr;

 

posted on 2019-11-16 15:46  流光若影  阅读(122)  评论(0编辑  收藏  举报