JDBC方式update,参数完全动态化
实例代码
public static void main(String[] args) {
//公共使用的两个集合,为了保证 column 和 value 的顺序保持一致,需要用到有序Map存放数据
Map<String, Object> setValueMap = new LinkedHashMap<>();
Map<String, Object> whereOptionMap = new LinkedHashMap<>();
setValueMap.put("name", "张三");
setValueMap.put("age", 11);
setValueMap.put("sex", "男");
setValueMap.put(null, "");
//原条件
whereOptionMap.put("name", "gyl");
whereOptionMap.put("age", 12);
whereOptionMap.put(null, "123");
whereOptionMap.put("sex", "女");
whereOptionMap.put(null, "");
whereOptionMap.put("phone", null);
setValueMap.remove(null);
whereOptionMap.remove(null);
System.out.println("setValueMap = " + setValueMap);
System.out.println("whereOptionMap = " + whereOptionMap);
//拼接setValue
StringJoiner setSQL = new StringJoiner(",", "set ", " ");
setValueMap.keySet().forEach(item -> setSQL.add(item + "=?"));
//拼接whereOption条件字符串
StringJoiner whereSQL = new StringJoiner(" and ", "where ", " ");
whereOptionMap.keySet().forEach(item -> whereSQL.add("nvl(" + item + ",'defaultValue')=nvl(?,'defaultValue')"));
System.out.println(setSQL);
System.out.println(whereSQL);
// 将两个集合的value值拼接,而后转成Object[]数组
System.out.println(setValueMap.values());
System.out.println(whereOptionMap.values());
ArrayList<Object> values = ListUtil.toList(setValueMap.values());
values.addAll(whereOptionMap.values());
System.out.println(values);
Object[] params = values.toArray();
//每次for循环用完之后清空掉
setValueMap.clear();
whereOptionMap.clear();
}
参考结果
setValueMap = {name=张三, age=11, sex=男}
whereOptionMap = {name=gyl, age=12, sex=女, phone=null}
set name=?,age=?,sex=?
where nvl(name,'defaultValue')=nvl(?,'defaultValue') and nvl(age,'defaultValue')=nvl(?,'defaultValue') and nvl(sex,'defaultValue')=nvl(?,'defaultValue') and nvl(phone,'defaultValue')=nvl(?,'defaultValue')
[张三, 11, 男]
[gyl, 12, 女, null]
[张三, 11, 男, gyl, 12, 女, null]