Procházet zdrojové kódy

标准接口完善统一的新增/更新接口

huangws před 2 týdny
rodič
revize
cdd97e35d3

+ 156 - 0
GetDataByRESTful/src/main/java/com/jyxt/getdatabyrestful/service/impl/BasicMethod.java

@@ -3,6 +3,7 @@ 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;
@@ -11,7 +12,9 @@ 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 {
@@ -20,9 +23,13 @@ public class BasicMethod {
     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()) {
@@ -245,5 +252,154 @@ public class BasicMethod {
         }
     }
 
+    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";
+    }
+
 
 }

+ 4 - 4
GetDataByView/src/main/java/com/jyxt/getdatabyview/HandleData.java

@@ -1,7 +1,7 @@
 package com.jyxt.getdatabyview;
 
+import com.jyxt.getdatabyview.view.repository.IBPSRepository;
 import com.jyxt.getdatabyview.view.repository.LISViewRepository;
-import com.jyxt.getdatabyview.view.repository.QualityIndicatorRepository;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -18,7 +18,7 @@ public class HandleData {
     private LISViewRepository lisViewRepository;
 
     @Autowired
-    private QualityIndicatorRepository qualityIndicatorRepository;
+    private IBPSRepository ibpsRepository;
 
     private static final String RESULT_DELIMITER = "\\^";
 
@@ -84,7 +84,7 @@ public class HandleData {
                     }
 //                    qualityIndicatorRepository.save(pingjiaId, resultValue,total,DataDetail,IsQualified);
                     //分子不需要整数
-                    qualityIndicatorRepository.save(pingjiaId, resultValue,resultValue,DataDetail,IsQualified);
+                    //ibpsRepository.save(pingjiaId, resultValue,resultValue,DataDetail,IsQualified);
                 }
             } else if (resultParts.length==3){
                 String numerator = resultParts[1];
@@ -116,7 +116,7 @@ public class HandleData {
                     } else if (QIIndex==18){
                         DataDetail = "危急值通报时间(从结果确认到与临床医生交流的时间)满足规定时间的检验项目数 "+resultParts[1]+" 例,同期需要危急值通报的检验项目总数 "+resultParts[2]+" 例";
                     }
-                    qualityIndicatorRepository.save(pingjiaId,resultValue,numerator,denominator,DataDetail,IsQualified);
+                    //ibpsRepository.save(pingjiaId,resultValue,numerator,denominator,DataDetail,IsQualified);
                 }
             } else {
                 log.info("no result to save:zhiliangzhibiao:{},bianzhishijian:{}",zhiliangzhibia,bianzhishijian);

+ 126 - 17
GetDataByView/src/main/java/com/jyxt/getdatabyview/view/repository/IBPSRepository.java

@@ -11,10 +11,12 @@ import org.springframework.stereotype.Repository;
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
 import java.sql.Timestamp;
+import java.sql.Types;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 
 @Repository
@@ -23,6 +25,9 @@ public class IBPSRepository {
     @Qualifier("secondJdbcTemplate")
     private JdbcTemplate jdbcTemplate;
 
+    @Value("${config.insertMode}")
+    private String insertMode;
+
     private static final Logger log = LoggerFactory.getLogger(IBPSRepository.class);
 
     public static List<Map<String, Object>> userList = new ArrayList<>();
@@ -38,23 +43,46 @@ public class IBPSRepository {
     }
 
 
-    public String saveToTable(List<Map<String, Object>> inputList, String TableName) {
+    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 {
-            // 获取第一个Map的字段名作为表字段
-            Map<String, Object> firstRow = inputList.get(0);
-            String columns = String.join(",", firstRow.keySet());
+            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);
 
-            // 构建占位符部分 (?,?,...)
-            String placeholders = String.join(",", Collections.nCopies(firstRow.size(), "?"));
+        log.info("executing insert sql: " + sql);
 
-            // 构建完整SQL语句
-            String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", TableName, columns, placeholders);
-            log.info("executing 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 {
@@ -64,10 +92,13 @@ public class IBPSRepository {
                         String key = entry.getKey();
                         Object value = entry.getValue();
 
-                        if (key.contains("Time") && value instanceof Timestamp) {
+                        if (value == null) {
+                            ps.setNull(index++, Types.VARCHAR);
+                        } else if (value instanceof Timestamp) {
                             ps.setTimestamp(index++, (Timestamp) value);
                         } else {
-                            ps.setString(index++, value != null ? value.toString() : null);
+                            // 其他所有类型转字符串(包括 Integer, Boolean, Date, String 等)
+                            ps.setString(index++, value.toString());
                         }
                     }
                 }
@@ -76,14 +107,92 @@ public class IBPSRepository {
                     return inputList.size();
                 }
             });
-            retValue = "success";
-        } catch (Exception e) {
-            e.printStackTrace();
-            return "insert failed:"+e.getMessage().split(";")[2];
+            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 retValue;
+        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";
+    }
+
+
     /**
      * 获取基础数据:
      * LIS系统用户名对应金通用户信息