StringBuilder sql = new StringBuilder(" WHERE "); for (Map.Entry<String, String> entry : query.entrySet()) { if (entry.getKey().contains(FindConfig.MIN_)) { String min = humpToLine(entry.getKey()).replace("_min", ""); sql.append("`"+min+"`").append(" >= '").append(URLDecoder.decode(entry.getValue(), "UTF-8")).append("' and "); continue; } if (entry.getKey().contains(FindConfig.MAX_)) { String max = humpToLine(entry.getKey()).replace("_max", ""); sql.append("`"+max+"`").append(" <= '").append(URLDecoder.decode(entry.getValue(), "UTF-8")).append("' and "); continue; } if (like == true) { sql.append("`"+humpToLine(entry.getKey())+"`").append(" LIKE '%").append(URLDecoder.decode(entry.getValue(), "UTF-8")).append("%'").append(" and "); } else { sql.append("`"+humpToLine(entry.getKey())+"`").append(" = '").append(URLDecoder.decode(entry.getValue(), "UTF-8")).append("'").append(" and "); } } if (sqlwhere!=null && !sqlwhere.trim().equals("")) { sql.append(sqlwhere).append(" and "); } sql.delete(sql.length() - 4, sql.length()); sql.append(" "); return sql.toString(); 写一个相似的生成where后面条件查询的方法
时间: 2023-06-16 14:02:39 浏览: 168
可以参考以下代码:
```
public static String generateWhereClause(Map<String, String> query, boolean like, String sqlWhere) throws UnsupportedEncodingException {
StringBuilder sql = new StringBuilder(" WHERE ");
for (Map.Entry<String, String> entry : query.entrySet()) {
String key = entry.getKey();
String value = URLDecoder.decode(entry.getValue(), "UTF-8");
if (key.contains(FindConfig.MIN_)) {
String min = humpToLine(key).replace("_min", "");
sql.append("`").append(min).append("`").append(" >= '").append(value).append("' and ");
} else if (key.contains(FindConfig.MAX_)) {
String max = humpToLine(key).replace("_max", "");
sql.append("`").append(max).append("`").append(" <= '").append(value).append("' and ");
} else if (like) {
sql.append("`").append(humpToLine(key)).append("`").append(" LIKE '%").append(value).append("%'").append(" and ");
} else {
sql.append("`").append(humpToLine(key)).append("`").append(" = '").append(value).append("'").append(" and ");
}
}
if (sqlWhere != null && !sqlWhere.trim().equals("")) {
sql.append(sqlWhere).append(" and ");
}
sql.delete(sql.length() - 4, sql.length());
sql.append(" ");
return sql.toString();
}
private static String humpToLine(String str) {
Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
StringBuilder builder = new StringBuilder(str);
int i = 0;
while (matcher.find()) {
builder.replace(matcher.start() + i, matcher.end() + i, "_" + matcher.group().toLowerCase());
i++;
}
if (builder.charAt(0) == '_') {
builder.deleteCharAt(0);
}
return builder.toString();
}
```
这段代码与之前的代码类似,但是有以下几个改进:
1. 将 `humpToLine` 方法提取出来,可以在其他方法中使用;
2. 将 `if-else if` 改为 `if-else`,可以让代码更加简洁;
3. 将解码逻辑提取出来,可以让代码更加清晰;
4. 代码中加入了一些空格,可以让生成的 SQL 更加美观。
阅读全文