public classSqlCondition {//职位:用于查询的条件判断
privateString title;//职位类型:用于查询的条件判断
privateInteger positiontype;publicSqlCondition() {super();
}publicString getTitle() {returntitle;
}public voidsetTitle(String title) {this.title =title;
}publicInteger getPositiontype() {returnpositiontype;
}public voidsetPositiontype(Integer positiontype) {this.positiontype =positiontype;
}/*** 查询语句的条件判断
* 方法一(推荐使用):*/
publicString getQueryCondition_01(){
String whereSql="";if(title !=null && !"".equals(title)){
whereSql+= " and title like '%"+title+"%'";
}if(positiontype!=null && !"".equals(positiontype)){
whereSql+=" and positiontype = "+positiontype;
}//replace:替换;First:第一个
return whereSql.replaceFirst("and", "where");
}/*** 查询语句的条件判断
* 方法二(不推荐使用): where 1==1 会影响查询的性能*/
publicString getQueryCondition_02(){
String whereSql= "where 1==1";if(title != null && !"".equals(title)){
whereSql+= "and title like '%"+title+"%'";
}if(positiontype !=null){
whereSql+= "and positiontype = " +positiontype;
}returnwhereSql;
}/*** 查询语句的条件判断
* 方法三(准备一个标识(即一个flag)
如果标识是true,条件前就加where,如果是false,条件前就加and):*/
publicString getQueryCondition_03(){//标识:flag
boolean flag = true;
String whereSql= "";//title不为null,并且不为空字符串
if(title!=null && !"".equals(title)){if(flag){
whereSql+= " where ";
flag= false;
}else{
whereSql+= " and ";
}
whereSql+= " title like '%"+title+"%' ";
}if(positiontype!=null){if(flag){
whereSql+= " where ";
flag= false;
}else{
whereSql+= " and ";
}
whereSql+= " positiontype = "+positiontype;
}returnwhereSql;
}/*** 查询语句的条件判断
* 方法四(准备一个集合):*/
publicString getQueryCondition_04(){//准备一个集合(里面会装咱们的所有条件)
List sqlList = new ArrayList<>();
String whereSql= "";//title不为null,并且不为空字符串
if(title!=null && !"".equals(title)){
sqlList.add(" title like '%"+title+"%' ");
}if(positiontype!=null){
sqlList.add(" positiontype = "+positiontype);
}//查询条件加多了,只要在这加if语句就可以了//遍历这个集合
for (int i = 0; i < sqlList.size(); i++) {if(i==0){//第一次循环,前面肯定是加where
whereSql += " where ";
}else{//第2-n次循环,前面肯定是加and
whereSql += " and ";
}
whereSql+=sqlList.get(i);
}returnwhereSql;
}