多條件查詢解決方案

public List<Customer> query(Customer customer){


//那麼我們怎麼來給出條件參數呢
//那麼還是來創建一個list吧,list可以直接toArray變成數組

List<Object> params=new ArrayList<Object>();
//給出sql語句前半句,以後再追加
StringBuilder sql=new StringBuilder("select * from customers where 1=1");
//切記,and  前面必須要加空格 否則會報 必須聲明變量 @p0and的異常 應該是在sqlserver中才會拋
if(customer.getName()!=null && !customer.getName().trim().isEmpty()){

sql.append(" and name like ?");
params.add("%"+customer.getName()+"%");
}
if(customer.getGender()!=null && !customer.getGender().trim().isEmpty()){

sql.append(" and gender like ?");

params.add("%"+customer.getGender()+"%");

}
if(customer.getCellphone()!=null && !customer.getCellphone().trim().isEmpty()){

sql.append(" and cellphone like ?");
params.add("%"+customer.getCellphone()+"%");
}
if(customer.getEmail()!=null && !customer.getEmail().trim().isEmpty()){

sql.append(" and email like ?");
params.add("%"+customer.getEmail()+"%");
}



try{

return qr.query(sql.toString(),new BeanListHandler<Customer>(Customer.class)
,params.toArray());
}catch(SQLException e){

throw new RuntimeException(e);

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章