我有一段有效的代码,但是,我想知道是否有可能在不使用计数器变量的情况下使其变得更好。我有一个“过滤器”映射,如果映射中至少有一件事情我想更改我的SQL字符串。
StringBuilder sb = new StringBuilder("SELECT * from Table");
if (filters.size() >= 1) {
int counter = 0; //I don't want to use this
for (String key : filters.keySet()) {
if (counter == 0) {
sb.append(" WHERE " + key + "=?");
counter= 1;
continue;
}
sb.append(" AND " + key + "=?");
}
}
最佳答案
您可以使用字符串连接器,该连接器允许设置一个空值,当您的设置为空时,它将不包含“ WHERE”。
StringJoiner joiner = new StringJoiner(" AND ", " WHERE ", "");
joiner.setEmptyValue("");
filters.keySet().stream().map( key -> key + " = ?" ).forEach(joiner::add);
String query = "SELECT * FROM TABLE" + joiner.toString();
没有流的替代方法:
StringJoiner joiner = new StringJoiner("=? AND ", " WHERE ", "=?");
joiner.setEmptyValue("");
filters.keySet().forEach(joiner::add);
String query = "SELECT * FROM TABLE" + joiner.toString();