在三層架構的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()。