Fork me on GitHub

QueryRunner使用之可变条件的处理

在三层架构的Dao层中,需要通过不确定的条件,从数据库查询结果。

可以利用List集合作为容器将条件存储起来。

实际开发中的代码:

 

public List<Hotel> searchByFloorAndTypeAndFree(String cmbHouseFloor,String cmbHouseType, String cheFree) throws SQLException {
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        //定义一个容器存储实际参数
        List<String> list = new ArrayList<String>();
        String sql = "select * from tb_hotel where 1 = 1";
        //如果用户选择了楼层
        int cmbHouseFloorInt = Integer.parseInt(cmbHouseFloor);
        if(cmbHouseFloorInt > 0){
            sql += " and houseId like ?";//模糊查询
            list.add(cmbHouseFloor + "%");
        }
        //如果用户选择了房型
        if(!cmbHouseType.equals("不限")){
            sql += " and houseType = ?";
            list.add(cmbHouseType);
        }
        //如果用户勾选了空闲复选框
        if(cheFree != null){
            sql += " and houseState = ?";
            list.add("%" + 0);
        }
        List<Hotel> hotelList = runner.query(sql, new BeanListHandler<Hotel>(Hotel.class), list.toArray());
        return hotelList;
    }

 

注意:根据runner.query的参数,可变参数需要String类型,所以需要将list转化为String即list.toArray()。


posted @ 2019-03-12 20:40  itzhouq  阅读(977)  评论(0编辑  收藏  举报