这个工具类是:2025年泛微OA专用接口数据入库工具类(原创) 的升级版,其实也不能算是升级版,主要是应对不同的业务。之前的是数据如果存在则直接跳过,这个版本是数据不存在新增,存在则按照主键更新,并且支持多个主键。
直接上代码:
package com.api.zp.interfaces.util;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import java.util.*;
import java.util.stream.Collectors;
/**
* @Author zF.
* @ClassName JsonToDbUpdateUtil.java
* @ProjectName 通用json数据入库/更新处理工具类
*/
public class JsonToDbUpdateUtil {
private static BaseBean base = new BaseBean();
/**
* 按数据库字段顺序将JSONObject写入或更新指定表
* @param rs 数据库连接
* @param tableName 目标数据库表名
* @param json 待写入的JSON对象
* @param customJson 自定义JSON参数,优先级高于原始json
* @param uniqueFields 唯一字段列表,数据去重使用,避免重复落库
*/
public static void upsertByDbFieldOrder(RecordSet rs, String tableName, JSONObject json, JSONObject customJson, List<String> uniqueFields) {
// 合并原始JSON与自定义JSON(自定义优先级更高)
JSONObject mergedJson = new JSONObject(json);
// 把json的所有key都转换成大写
JSONObject convertedJson = convertKeysToUpperCase(mergedJson);
if(customJson != null) {
convertedJson.putAll(customJson);
}
// 转换唯一字段为大写
List<String> upperUniqueFields = uniqueFields.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// 验证所有唯一字段在JSON中存在
for (String field : upperUniqueFields) {
if (!convertedJson.containsKey(field)) {
base.writeLog("错误:唯一字段[" + field + "]在JSON中不存在,操作终止!");
return;
}
}
// 构建WHERE条件
StringBuilder whereClause = new StringBuilder();
List<Object> whereParams = new ArrayList<>();
for (String field : upperUniqueFields) {
if (whereClause.length() > 0) {
whereClause.append(" AND ");
}
whereClause.append(field).append(" = ?");
whereParams.add(convertedJson.get(field));
}
// 检查记录是否存在
String checkSql = "SELECT COUNT(1) AS CNT FROM " + tableName + " WHERE " + whereClause;
boolean exists = false;
try {
rs.executeQuery(checkSql, whereParams.toArray());
if (rs.next()) {
exists = rs.getInt("CNT") > 0;
}
} catch (Exception e) {
base.writeLog("检查记录存在性失败!表[" + tableName + "],错误:" + e.getMessage());
throw new RuntimeException("记录检查异常!", e);
}
// 获取数据库字段列表
List<String> dbFields = getTableFields(rs, tableName, convertedJson);
if (dbFields.isEmpty()) {
base.writeLog("警告:表 [" + tableName + "] 无有效字段信息,操作终止!");
return;
}
if (exists) {
// 更新操作
executeUpdate(rs, tableName, convertedJson, dbFields, whereClause.toString(), whereParams);
} else {
// 插入操作
executeInsert(rs, tableName, convertedJson, dbFields);
}
}
/**
* 执行更新操作
*/
private static void executeUpdate(RecordSet rs, String tableName, JSONObject json,
List<String> dbFields, String whereClause, List<Object> whereParams) {
StringBuilder setClause = new StringBuilder();
List<Object> setParams = new ArrayList<>();
for (String field : dbFields) {
// 跳过唯一字段,它们用于WHERE条件
if (whereClause.contains(field + " = ?")) {
continue;
}
if (setClause.length() > 0) {
setClause.append(", ");
}
setClause.append(field).append(" = ?");
setParams.add(json.get(field));
}
String sql = "UPDATE " + tableName + " SET " + setClause + " WHERE " + whereClause;
List<Object> allParams = new ArrayList<>();
allParams.addAll(setParams);
allParams.addAll(whereParams);
try {
rs.executeUpdate(sql, allParams.toArray());
base.writeLog("成功更新表 [" + tableName + "],数据:" + json.toJSONString());
} catch (Exception e) {
base.writeLog("更新失败!表 [" + tableName + "],错误:" + e.getMessage());
throw new RuntimeException("数据库更新异常", e);
}
}
/**
* 执行插入操作
*/
private static void executeInsert(RecordSet rs, String tableName, JSONObject json, List<String> dbFields) {
List<Object> params = new ArrayList<>();
for (String field : dbFields) {
params.add(json.get(field));
}
String fieldsClause = String.join(", ", dbFields);
String placeholders = String.join(", ", Collections.nCopies(dbFields.size(), "?"));
String sql = "INSERT INTO " + tableName + "(" + fieldsClause + ") VALUES(" + placeholders + ")";
try {
rs.executeUpdate(sql, params.toArray());
base.writeLog("成功插入表 [" + tableName + "],数据:" + json.toJSONString());
} catch (Exception e) {
base.writeLog("插入失败!表 [" + tableName + "],错误:" + e.getMessage());
throw new RuntimeException("数据库插入异常", e);
}
}
/**
* 获取数据库表的字段列表(按定义顺序)
*/
private static List<String> getTableFields(RecordSet metaRs, String tableName, JSONObject json) {
List<String> fields = new ArrayList<>();
String metaSql = "SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS " +
"WHERE TABLE_NAME = '" + tableName + "' AND OWNER = USER " +
"ORDER BY COLUMN_ID";
try {
metaRs.execute(metaSql);
while (metaRs.next()) {
String field = metaRs.getString("COLUMN_NAME");
if(json.containsKey(field)) {
fields.add(field);
}
}
if(fields.isEmpty()) {
base.writeLog("警告:表 [" + tableName + "] 无JSON中存在的有效字段,操作终止!");
}
} catch (Exception e) {
base.writeLog("获取表字段失败!表 [" + tableName + "],错误:" + e.getMessage());
throw new RuntimeException("元数据查询异常!", e);
}
return fields;
}
/**
* 递归转换JSON对象的所有key为大写
*/
public static JSONObject convertKeysToUpperCase(JSONObject json) {
if (json == null) {
return null;
}
JSONObject result = new JSONObject();
for (Object ikey : json.keySet()) {
String key = StrUtil.toString(ikey);
Object value = json.get(key);
String upperKey = key.toUpperCase();
result.put(upperKey, processValue(value));
}
return result;
}
private static Object processValue(Object value) {
if (value instanceof JSONObject) {
return convertKeysToUpperCase((JSONObject) value);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
JSONArray newArray = new JSONArray();
array.forEach(item -> newArray.add(processValue(item)));
return newArray;
}
return value;
}
}
使用方式示例:
/**
* 更新联系人列表
* @param contactList 单个联系人对象
*/
public static Map<String, Object> UpdateContactList(RecordSet rs, JSONObject contactList, Map<String, Object> result, String date, String time) {
// 参数校验
if (ObjectUtil.isEmpty(contactList)) {
result.put("TYPE", "S");
result.put("MESSAGE", "contactList为空!");
return result;
}
// UUID
String randomUUID = IdUtil.randomUUID();
// 需要插入字段的表名
String tableName = "UF_BG_KSLXR";
// 查询指定字段并重新赋值
String ksmc = contactList.getString("ksmc");
String theKS = fieldQueryBy193(rs, "ID", ksmc);
// 新建自定义json(存入自定义字段)
JSONObject customJson = new JSONObject();
customJson.put("FORMMODEID", 2004);
customJson.put("MODEDATACREATER", 1);
customJson.put("MODEDATACREATERTYPE", 0);
customJson.put("MODEDATACREATEDATE", date);
customJson.put("MODEDATACREATETIME", time);
customJson.put("MODEUUID", randomUUID);
// 重新赋值字段
customJson.put("KSMC", theKS);
// 唯一字段(数据去重使用)
List<String> uniqueFields = Arrays.asList("KSMC", "LXR");
// 数据入库
JsonToDbUpdateUtil.upsertByDbFieldOrder(rs, tableName, contactList, customJson, uniqueFields);
result.put("TYPE", "S");
result.put("MESSAGE", "数据推送成功");
result.put("DATA", null);
return result;