多条件查询解决方案

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);

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