|
|
@@ -1,405 +0,0 @@
|
|
|
-package com.jyxt.getdatabyrestful.service.impl;
|
|
|
-
|
|
|
-import org.slf4j.Logger;
|
|
|
-import org.slf4j.LoggerFactory;
|
|
|
-import org.springframework.beans.factory.annotation.Autowired;
|
|
|
-import org.springframework.beans.factory.annotation.Value;
|
|
|
-import org.springframework.dao.DataAccessException;
|
|
|
-import org.springframework.jdbc.core.BatchPreparedStatementSetter;
|
|
|
-import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
-import org.springframework.stereotype.Component;
|
|
|
-
|
|
|
-import java.sql.PreparedStatement;
|
|
|
-import java.sql.SQLException;
|
|
|
-import java.sql.Timestamp;
|
|
|
-import java.sql.Types;
|
|
|
-import java.util.*;
|
|
|
-import java.util.stream.Collectors;
|
|
|
-
|
|
|
-@Component
|
|
|
-public class BasicMethod {
|
|
|
- private static final Logger log = LoggerFactory.getLogger(BasicMethod.class);
|
|
|
-
|
|
|
- public static List<Map<String, Object>> userList = new ArrayList<>();
|
|
|
- public static List<Map<String, Object>> posiList = new ArrayList<>();
|
|
|
-
|
|
|
-
|
|
|
- @Autowired
|
|
|
- private JdbcTemplate jdbcTemplate;
|
|
|
-
|
|
|
- @Value("${config.insertMode}")
|
|
|
- private String insertMode;
|
|
|
-
|
|
|
- public String saveToTable(List<Map<String, Object>> inputList, String TableName) {
|
|
|
- String retValue = "fail";
|
|
|
- if (inputList == null || inputList.isEmpty() || TableName == null || TableName.trim().isEmpty()) {
|
|
|
- return retValue;
|
|
|
- }
|
|
|
- try {
|
|
|
- // 获取第一个Map的字段名作为表字段
|
|
|
- Map<String, Object> firstRow = inputList.get(0);
|
|
|
- String columns = String.join(",", firstRow.keySet());
|
|
|
-
|
|
|
- // 构建占位符部分 (?,?,...)
|
|
|
- String placeholders = String.join(",", Collections.nCopies(firstRow.size(), "?"));
|
|
|
-
|
|
|
- // 构建完整SQL语句
|
|
|
- String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", TableName, columns, placeholders);
|
|
|
- log.info("executing sql: " + sql);
|
|
|
- // 批量执行
|
|
|
- jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
|
|
- @Override
|
|
|
- public void setValues(PreparedStatement ps, int i) throws SQLException {
|
|
|
- Map<String, Object> row = inputList.get(i);
|
|
|
- int index = 1;
|
|
|
- for (Map.Entry<String, Object> entry : row.entrySet()) {
|
|
|
- String key = entry.getKey();
|
|
|
- Object value = entry.getValue();
|
|
|
-
|
|
|
- if (key.contains("Time") && value instanceof Timestamp) {
|
|
|
- ps.setTimestamp(index++, (Timestamp) value);
|
|
|
- } else {
|
|
|
- ps.setString(index++, value.toString());
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
- @Override
|
|
|
- public int getBatchSize() {
|
|
|
- return inputList.size();
|
|
|
- }
|
|
|
- });
|
|
|
- retValue = "success";
|
|
|
- } catch (Exception e) {
|
|
|
- e.printStackTrace();
|
|
|
- return "insert failed:"+e.getMessage().split(";")[2];
|
|
|
- }
|
|
|
- return retValue;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 获取基础数据:
|
|
|
- * LIS系统用户名对应金通用户信息
|
|
|
- */
|
|
|
- public void getBasicData(){
|
|
|
- String sqlUser = "select id_,name_,positions_ from ibps_party_employee where status_='actived'";
|
|
|
- userList = jdbcTemplate.queryForList(sqlUser);
|
|
|
- String sqlPosi = "select * from ibps_party_position";
|
|
|
- posiList = jdbcTemplate.queryForList(sqlPosi);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 返回用户ID@部门ID@部门名称
|
|
|
- * @param userName
|
|
|
- * @return
|
|
|
- */
|
|
|
- public String getUserInfoByName(String userName){
|
|
|
- String retVal = "-1";
|
|
|
- for (Map<String, Object> map : userList) {
|
|
|
- if (map.get("name_").toString().equals(userName)) {
|
|
|
- String userId = (String) map.get("id_");
|
|
|
- String positionId = String.valueOf(map.get("positions_")).split(",")[0];
|
|
|
- String positionName = (String) getPosiByID(positionId);
|
|
|
- if (!positionName.equals("-1")) {
|
|
|
- retVal = userId+"@"+positionId+"@"+positionName;
|
|
|
- }else{
|
|
|
- retVal = "-1^部门:"+positionName+"未找到!";
|
|
|
- return retVal;
|
|
|
- }
|
|
|
- return retVal;
|
|
|
- }
|
|
|
- retVal = "-1^用户:"+userName+"未找到!";
|
|
|
- }
|
|
|
- return retVal;
|
|
|
- }
|
|
|
-
|
|
|
- public String getPosiByID(String positionId){
|
|
|
- String retVal = "-1";
|
|
|
- for (Map<String, Object> map : posiList) {
|
|
|
- if (map.get("id_").toString().equals(positionId)) {
|
|
|
- retVal = map.get("name_").toString();
|
|
|
- break;
|
|
|
- }
|
|
|
- }
|
|
|
- return retVal;
|
|
|
- }
|
|
|
-
|
|
|
- public List<Map<String, Object>> getQualityIndicatorItem(){
|
|
|
- String qryStr = "select tong_ji_pin_lv_ as Frequency,zhi_liang_zhi_bia as Target,yun_suan_fu_hao_ as Operator,zhi_biao_xian_zhi as LimitValue,dan_wei_ as Unit " +
|
|
|
- "from t_zlzbpzzb where shi_fou_qi_yong_='Y' and bei_zhu_ like '%LIS导入%' and zhi_liang_zhi_bia is not null";
|
|
|
- List<Map<String, Object>> QualityIndicatorList = jdbcTemplate.queryForList(qryStr);
|
|
|
- return QualityIndicatorList;
|
|
|
- }
|
|
|
-
|
|
|
- public List<Map<String, Object>> getUndoQualityIndicatorItem(){
|
|
|
- String qryStr = "select bian_zhi_shi_jian as StatDate,tong_ji_pin_lv_ as Frequency,zhi_liang_zhi_bia as Target," +
|
|
|
- "SUBSTRING_INDEX(yuan_shi_shu_ju_, '@', 1) AS Operator," +
|
|
|
- "SUBSTRING_INDEX(SUBSTRING_INDEX(yuan_shi_shu_ju_, '@', 2), '@', -1) AS LimitValue," +
|
|
|
- "SUBSTRING_INDEX(yuan_shi_shu_ju_, '@', -1) AS Unit from t_zlzbpjzb where zhuang_tai_='待处理'";
|
|
|
- List<Map<String, Object>> allUndoQualityIndicatorList = jdbcTemplate.queryForList(qryStr);
|
|
|
- return allUndoQualityIndicatorList;
|
|
|
- }
|
|
|
-
|
|
|
- public String updateToTable(Map<String, Object> conditionData, Map<String, Object> updateData, String TableName){
|
|
|
- String retVal = "fail";
|
|
|
- // 验证输入数据有效性
|
|
|
- if (updateData == null || updateData.isEmpty()) {
|
|
|
- log.warn("Update failed: updateData is null or empty");
|
|
|
- return "fail: updateData is null or empty";
|
|
|
- }
|
|
|
- if (conditionData == null || conditionData.isEmpty()) {
|
|
|
- log.warn("Update failed: conditionData is null or empty");
|
|
|
- return "fail: conditionData is null or empty";
|
|
|
- }
|
|
|
- try {
|
|
|
- // 1. 构建动态SET子句
|
|
|
- StringBuilder setClause = new StringBuilder();
|
|
|
- List<Object> params = new ArrayList<>();
|
|
|
- for (Map.Entry<String, Object> entry : updateData.entrySet()) {
|
|
|
- String column = validateColumnName(entry.getKey());
|
|
|
- if (column == null) {
|
|
|
- String error = "Invalid update column name: " + entry.getKey();
|
|
|
- log.warn("Update failed: {}", error);
|
|
|
- return "fail: " + error;
|
|
|
- }
|
|
|
- if (setClause.length() > 0) setClause.append(", ");
|
|
|
- setClause.append(column).append(" = ?");
|
|
|
- params.add(entry.getValue());
|
|
|
- }
|
|
|
- // 2. 构建动态WHERE子句
|
|
|
- StringBuilder whereClause = new StringBuilder();
|
|
|
- for (Map.Entry<String, Object> entry : conditionData.entrySet()) {
|
|
|
- String column = validateColumnName(entry.getKey());
|
|
|
- if (column == null) {
|
|
|
- String error = "Invalid condition column name: " + entry.getKey();
|
|
|
- log.warn("Update failed: {}", error);
|
|
|
- return "fail: " + error;
|
|
|
- }
|
|
|
- if (whereClause.length() > 0) whereClause.append(" AND ");
|
|
|
- whereClause.append(column).append(" = ?");
|
|
|
- params.add(entry.getValue());
|
|
|
- }
|
|
|
- // 3. 验证表名
|
|
|
- if (!isValidTableName(TableName)) {
|
|
|
- String error = "Invalid table name: " + TableName;
|
|
|
- log.warn("Update failed: {}", error);
|
|
|
- return "fail: " + error;
|
|
|
- }
|
|
|
- // 4. 构建完整SQL语句
|
|
|
- String sql = "UPDATE " + TableName + " SET " + setClause +
|
|
|
- " WHERE " + whereClause;
|
|
|
- // 5. 记录SQL语句和参数到日志
|
|
|
- logSQLWithParams(sql, params);
|
|
|
- // 6. 执行更新操作
|
|
|
- int rowsAffected = jdbcTemplate.update(sql, params.toArray());
|
|
|
-
|
|
|
- // 7. 记录更新结果
|
|
|
- if (rowsAffected > 0) {
|
|
|
- log.info("Update successful: {} row(s) affected in table '{}'", rowsAffected, TableName);
|
|
|
- return "success";
|
|
|
- } else {
|
|
|
- log.warn("Update completed but no rows affected in table '{}'", TableName);
|
|
|
- return "fail: no rows updated";
|
|
|
- }
|
|
|
- } catch (DataAccessException e) {
|
|
|
- String error = "Database error: " + e.getMessage();
|
|
|
- log.error("Update failed: {}", error, e);
|
|
|
- return "fail: " + error;
|
|
|
- } catch (Exception e) {
|
|
|
- String error = "System error: " + e.getMessage();
|
|
|
- log.error("Update failed: {}", error, e);
|
|
|
- return "fail: " + error;
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // 列名校验方法
|
|
|
- private String validateColumnName(String columnName) {
|
|
|
- // 只允许字母、数字和下划线
|
|
|
- if (columnName == null || !columnName.matches("[a-zA-Z0-9_]+")) {
|
|
|
- return null;
|
|
|
- }
|
|
|
- return columnName;
|
|
|
- }
|
|
|
-
|
|
|
- // 表名校验方法
|
|
|
- private boolean isValidTableName(String tableName) {
|
|
|
- // 可根据需要扩展校验规则
|
|
|
- return tableName != null && tableName.matches("[a-zA-Z0-9_]+");
|
|
|
- }
|
|
|
-
|
|
|
- // 记录SQL语句和参数
|
|
|
- private void logSQLWithParams(String sql, List<Object> params) {
|
|
|
- if (log.isInfoEnabled()) {
|
|
|
- StringBuilder logMessage = new StringBuilder("Executing SQL: \n");
|
|
|
- logMessage.append(sql);
|
|
|
-
|
|
|
- if (params != null && !params.isEmpty()) {
|
|
|
- logMessage.append("\nParameters: [");
|
|
|
- for (int i = 0; i < params.size(); i++) {
|
|
|
- if (i > 0) logMessage.append(", ");
|
|
|
-
|
|
|
- Object param = params.get(i);
|
|
|
- // 对字符串添加引号
|
|
|
- if (param instanceof String) {
|
|
|
- logMessage.append("'").append(param).append("'");
|
|
|
- } else {
|
|
|
- logMessage.append(param);
|
|
|
- }
|
|
|
- }
|
|
|
- logMessage.append("]");
|
|
|
- }
|
|
|
-
|
|
|
- log.info(logMessage.toString());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- public String saveToTable(List<Map<String, Object>> inputList, String TableName, String saveType) {
|
|
|
- String retValue = "fail";
|
|
|
- if (inputList == null || inputList.isEmpty() || TableName == null || TableName.trim().isEmpty()) {
|
|
|
- return retValue;
|
|
|
- }
|
|
|
-
|
|
|
- // 验证 saveType 参数
|
|
|
- if (!"1".equals(saveType) && !"2".equals(saveType)) {
|
|
|
- return "invalid saveType, must be '1' or '2'";
|
|
|
- }
|
|
|
-
|
|
|
- try {
|
|
|
- if ("1".equals(saveType)) {
|
|
|
- // 原有插入逻辑
|
|
|
- retValue = executeInsert(inputList, TableName);
|
|
|
- } else if ("2".equals(saveType)) {
|
|
|
- // 新增更新逻辑
|
|
|
- retValue = executeUpdate(inputList, TableName);
|
|
|
- }
|
|
|
- } catch (Exception e) {
|
|
|
- e.printStackTrace();
|
|
|
- String errorMsg = "1".equals(saveType) ? "insert" : "update";
|
|
|
- return errorMsg + " failed:" + (e.getMessage() != null ? e.getMessage().split(";")[0] : e.getMessage());
|
|
|
- }
|
|
|
- return retValue;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行插入操作
|
|
|
- */
|
|
|
- private String executeInsert(List<Map<String, Object>> inputList, String TableName) {
|
|
|
- Map<String, Object> firstRow = inputList.get(0);
|
|
|
- String columns = String.join(",", firstRow.keySet());
|
|
|
- String placeholders = String.join(",", Collections.nCopies(firstRow.size(), "?"));
|
|
|
- String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", TableName, columns, placeholders);
|
|
|
-
|
|
|
- log.info("executing insert sql: " + sql);
|
|
|
-
|
|
|
- if (insertMode.equals("1")) {
|
|
|
- log.info("ready to insert " + inputList.size() + " records");
|
|
|
- jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
|
|
- @Override
|
|
|
- public void setValues(PreparedStatement ps, int i) throws SQLException {
|
|
|
- Map<String, Object> row = inputList.get(i);
|
|
|
- int index = 1;
|
|
|
- for (Map.Entry<String, Object> entry : row.entrySet()) {
|
|
|
- String key = entry.getKey();
|
|
|
- Object value = entry.getValue();
|
|
|
-
|
|
|
- if (value == null) {
|
|
|
- ps.setNull(index++, Types.VARCHAR);
|
|
|
- } else if (value instanceof Timestamp) {
|
|
|
- ps.setTimestamp(index++, (Timestamp) value);
|
|
|
- } else {
|
|
|
- // 其他所有类型转字符串(包括 Integer, Boolean, Date, String 等)
|
|
|
- ps.setString(index++, value.toString());
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
- @Override
|
|
|
- public int getBatchSize() {
|
|
|
- return inputList.size();
|
|
|
- }
|
|
|
- });
|
|
|
- log.info("insert completed successfully");
|
|
|
- } else {
|
|
|
- log.info("------qry mode, pretend to insert " + inputList.size() + " records-------");
|
|
|
- inputList.forEach(map -> {
|
|
|
- StringBuilder sb = new StringBuilder();
|
|
|
- map.forEach((k, v) -> sb.append(k).append(":").append(v).append(","));
|
|
|
- if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
|
|
|
- log.info("Insert data: " + sb.toString());
|
|
|
- });
|
|
|
- }
|
|
|
- return "success";
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行更新操作
|
|
|
- */
|
|
|
- private String executeUpdate(List<Map<String, Object>> inputList, String TableName) {
|
|
|
- // 检查是否包含 id_ 字段
|
|
|
- Map<String, Object> firstRow = inputList.get(0);
|
|
|
- if (!firstRow.containsKey("id_")) {
|
|
|
- return "update failed: missing 'id_' field in input data";
|
|
|
- }
|
|
|
-
|
|
|
- // 构建更新SQL (排除id_字段,因为它作为WHERE条件)
|
|
|
- List<String> columns = firstRow.keySet().stream()
|
|
|
- .filter(key -> !"id_".equals(key))
|
|
|
- .collect(Collectors.toList());
|
|
|
-
|
|
|
- String setClause = columns.stream()
|
|
|
- .map(column -> column + " = ?")
|
|
|
- .collect(Collectors.joining(","));
|
|
|
-
|
|
|
- String sql = String.format("UPDATE %s SET %s WHERE id_ = ?", TableName, setClause);
|
|
|
-
|
|
|
- log.info("executing update sql: " + sql);
|
|
|
-
|
|
|
- if (insertMode.equals("1")) {
|
|
|
- log.info("ready to update " + inputList.size() + " records");
|
|
|
- jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
|
|
|
- @Override
|
|
|
- public void setValues(PreparedStatement ps, int i) throws SQLException {
|
|
|
- Map<String, Object> row = inputList.get(i);
|
|
|
- int index = 1;
|
|
|
-
|
|
|
- // 设置SET部分的参数
|
|
|
- for (String column : columns) {
|
|
|
- Object value = row.get(column);
|
|
|
- if (value == null) {
|
|
|
- ps.setNull(index++, Types.VARCHAR);
|
|
|
- } else if (value instanceof Timestamp) {
|
|
|
- ps.setTimestamp(index++, (Timestamp) value);
|
|
|
- } else {
|
|
|
- ps.setString(index++, value.toString());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // 设置WHERE条件的id_参数
|
|
|
- Object idValue = row.get("id_");
|
|
|
- if (idValue == null) {
|
|
|
- ps.setNull(index, Types.VARCHAR);
|
|
|
- } else if (idValue instanceof Timestamp) {
|
|
|
- ps.setTimestamp(index, (Timestamp) idValue);
|
|
|
- } else {
|
|
|
- ps.setString(index, idValue.toString());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- @Override
|
|
|
- public int getBatchSize() {
|
|
|
- return inputList.size();
|
|
|
- }
|
|
|
- });
|
|
|
- log.info("update completed successfully");
|
|
|
- } else {
|
|
|
- log.info("------qry mode, pretend to update " + inputList.size() + " records-------");
|
|
|
- inputList.forEach(map -> {
|
|
|
- StringBuilder sb = new StringBuilder();
|
|
|
- map.forEach((k, v) -> sb.append(k).append(":").append(v).append(","));
|
|
|
- if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
|
|
|
- log.info("Update data (id_=" + map.get("id_") + "): " + sb.toString());
|
|
|
- });
|
|
|
- }
|
|
|
- return "success";
|
|
|
- }
|
|
|
-
|
|
|
-
|
|
|
-}
|