拼接查詢條件為list集合的sql函式
阿新 • • 發佈:2019-02-15
當deptId 為1時 sql語句不做更改
當deptId 為其他數字時 list中的id項作為sql查詢條件
剛開始編寫的時候思路是用or語句進行迴圈遍歷 重複加上or的sql語句來查詢
發現比較複雜 最後採取了sql的in函式來實現
public String getDeptIdSql(List<Long> deptIdList){
Iterator<Long> it = deptIdList.iterator();
//當部門id為1時 不採用篩選
while(it.hasNext()){
Long deptId = it.next();
if (deptId == 1){
return "";
}
}
//拼接in條件語句
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get (i);
}
}
String sql = " and mtMaintenanceStandard.dept_Id in (" + s + ") ";
return sql;
}
編寫完成後發現函式有可以提高函式的複用性,將mtMaintenanceStandard.dept_Id設為傳入的變數
最後得到
public String getDeptIdSql(String condition,List<Long> deptIdList){
Iterator<Long> it = deptIdList.iterator();
//當部門id為1時 不採用篩選
while(it.hasNext()){
Long deptId = it.next();
if(deptId == 1){
return "";
}
}
//拼接in條件語句
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get(i);
}
}
String sql = " and " + condition + " in (" + s + ") ";
return sql;
}
更為通用的版本是不用判斷deptId是否為1
public String getDeptIdSql(String condition,List<Long> deptIdList){
String s = "";
for(int i = 0; i < deptIdList.size();i++){
if(i!=(deptIdList.size()-1)){
s += deptIdList.get(i) + ",";
}else{
s += deptIdList.get(i);
}
}
String sql = " and " + condition + " in (" + s + ") ";
return sql;
}