拼接查询条件为list集合的sql函数

xiaoxiao2021-02-28  121

当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; }
转载请注明原文地址: https://www.6miu.com/read-18888.html

最新回复(0)