|
@@ -0,0 +1,855 @@
|
|
|
+package org.bfkj.utils;
|
|
|
+
|
|
|
+import com.zaxxer.hikari.HikariConfig;
|
|
|
+import com.zaxxer.hikari.HikariDataSource;
|
|
|
+import org.bfkj.config.AppConfig;
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
+import org.springframework.jdbc.support.GeneratedKeyHolder;
|
|
|
+import org.springframework.jdbc.support.KeyHolder;
|
|
|
+
|
|
|
+import java.sql.*;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.*;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
+import java.util.regex.Matcher;
|
|
|
+import java.util.regex.Pattern;
|
|
|
+
|
|
|
+public class MyDbHelper {
|
|
|
+
|
|
|
+ private HikariDataSource theDataSource;
|
|
|
+ private JdbcTemplate theJdbcTemplate;
|
|
|
+
|
|
|
+ private String connectConfig;
|
|
|
+
|
|
|
+ private List<String> tableList = new ArrayList<>();
|
|
|
+ private Map<String, List<String>> tableColumn = new HashMap<>();
|
|
|
+ private Map<String, List<String>> tablePrimaryKey = new HashMap<>();
|
|
|
+ private HashMap<String, Map<String, List<String>>> sqlColumn = new HashMap<>();
|
|
|
+ private ConcurrentHashMap<String, List<Object>> event6Map = new ConcurrentHashMap<>();
|
|
|
+ private Map<String, String> eventSQL = new HashMap<>() {{
|
|
|
+ put("0", "select * from 表名");
|
|
|
+ put("1", "insert into 表名(字段) values(值) ");
|
|
|
+ put("2", "update 表名 set 字段 ");
|
|
|
+ put("3", "delete from 表名 ");
|
|
|
+
|
|
|
+ }};
|
|
|
+ private static String errorMessage = null;
|
|
|
+
|
|
|
+ public MyDbHelper(String connectStr) {
|
|
|
+ Connection theConnect = null;
|
|
|
+ ResultSet tablesRsesult = null;
|
|
|
+ try {
|
|
|
+ connectConfig = connectStr;
|
|
|
+ Map<String, Object> connectMaps = MapTools.jsonStringToMap(connectStr);
|
|
|
+ if (connectMaps == null || Objects.isNull(connectMaps.get("url")) || Objects.isNull(connectMaps.get("driver-class-name"))) {
|
|
|
+ errorMessage = "数据库连接字符串非法: " + connectStr;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ HikariConfig config = new HikariConfig();
|
|
|
+ config.setMaximumPoolSize(6);
|
|
|
+ config.setKeepaliveTime(60000);
|
|
|
+ config.setMaxLifetime(60000 * 60 * 4);
|
|
|
+ config.addDataSourceProperty("cachePrepStmts", "true");
|
|
|
+ config.addDataSourceProperty("prepStmtCacheSize", "250");
|
|
|
+ config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
|
|
+ config.addDataSourceProperty("useServerPrepStmts", "true");
|
|
|
+ config.addDataSourceProperty("useLocalSessionState", "true");
|
|
|
+ config.addDataSourceProperty("useLocalTransactionState", "true");
|
|
|
+ config.addDataSourceProperty("rewriteBatchedStatements", "true");
|
|
|
+ config.addDataSourceProperty("cacheResultSetMetadata", "true");
|
|
|
+ config.addDataSourceProperty("cacheServerConfiguration", "true");
|
|
|
+ config.addDataSourceProperty("elideSetAutoCommits", "true");
|
|
|
+ config.addDataSourceProperty("maintainTimeStats", "false");
|
|
|
+ if (Objects.nonNull(connectMaps.get("username"))) {
|
|
|
+ config.setUsername(connectMaps.get("username").toString());
|
|
|
+ }
|
|
|
+ if (Objects.nonNull(connectMaps.get("password"))) {
|
|
|
+ config.setPassword(connectMaps.get("password").toString());
|
|
|
+ }
|
|
|
+ config.setJdbcUrl(connectMaps.get("url").toString());
|
|
|
+ config.setDriverClassName(connectMaps.get("driver-class-name").toString());
|
|
|
+ theDataSource = new HikariDataSource(config);
|
|
|
+ theJdbcTemplate = new JdbcTemplate(theDataSource);
|
|
|
+
|
|
|
+
|
|
|
+ theConnect = theDataSource.getConnection();
|
|
|
+ DatabaseMetaData tempMetaData = theConnect.getMetaData();
|
|
|
+ tablesRsesult = tempMetaData.getTables(theConnect.getCatalog(), theConnect.getCatalog(), null, new String[]{"TABLE"});
|
|
|
+ while (tablesRsesult.next()) {
|
|
|
+ tableList.add(tablesRsesult.getString("TABLE_NAME"));
|
|
|
+ }
|
|
|
+
|
|
|
+ } catch (Exception e) {
|
|
|
+ errorMessage = LogUtils.getException(e);
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ if (tablesRsesult != null) {
|
|
|
+ tablesRsesult.close();
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ System.out.println("MyDbHelper对象初始化时,关闭获取数据库信息的ResultSet出错: " + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ if (theConnect != null) {
|
|
|
+ theConnect.close();
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ System.out.println("MyDbHelper对象初始化时,关闭获取数据库信息的Connection出错:" + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void close() {
|
|
|
+ if (Objects.nonNull(theDataSource) && theDataSource.isRunning()) {
|
|
|
+ theDataSource.close();
|
|
|
+ }
|
|
|
+ theJdbcTemplate = null;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ public Map<String, Object> processSuccess(Object returnData, String sql, Object params) {
|
|
|
+
|
|
|
+ Map<String, Object> returnMap = new HashMap<>();
|
|
|
+ returnMap.put("code", "0");
|
|
|
+ returnMap.put("returnData", returnData);
|
|
|
+ returnMap.put("sql", sql);
|
|
|
+ returnMap.put("params", MapTools.jacksonObjToStr(params));
|
|
|
+ return returnMap;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ public Map<String, Object> processFail(String errorMessage, String sql, Object params) {
|
|
|
+ Map<String, Object> returnMap = new HashMap<>();
|
|
|
+ returnMap.put("code", "-1");
|
|
|
+ returnMap.put("message", errorMessage);
|
|
|
+ returnMap.put("sql", sql);
|
|
|
+ returnMap.put("params", MapTools.jacksonObjToStr(params));
|
|
|
+ return returnMap;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ public Map<String, Object> execute(String sql) {
|
|
|
+ try {
|
|
|
+ theJdbcTemplate.execute(sql);
|
|
|
+ return processSuccess(null, sql, null);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("执行创建表错误: " + LogUtils.getException(e), sql, null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * 根据条件查询,返回Lit<Map<String,Object>
|
|
|
+ *
|
|
|
+ * @param sql
|
|
|
+ * @param params
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public Map<String, Object> queryByParamsReturnList(String sql, Object... params) {
|
|
|
+ try {
|
|
|
+ return processSuccess(theJdbcTemplate.queryForList(sql, params), sql, params);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("根据条件查询异常" + LogUtils.getException(e), sql, params);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * jdbcTemplate 增加、删除 、修改
|
|
|
+ *
|
|
|
+ * @param sql 执行语句
|
|
|
+ * @param batchPm 批量执行参数
|
|
|
+ * @param params 单挑执行参数
|
|
|
+ * @return sql执行返回结果
|
|
|
+ */
|
|
|
+ public Map<String, Object> updateByCondition(String sql, List<Object[]> batchPm, Object... params) {
|
|
|
+ try {
|
|
|
+ Object tempObject;
|
|
|
+ if (Objects.nonNull(batchPm) && batchPm.get(0) != null) {
|
|
|
+ tempObject = theJdbcTemplate.batchUpdate(sql, batchPm);
|
|
|
+ } else {
|
|
|
+ tempObject = theJdbcTemplate.update(sql, params);
|
|
|
+ }
|
|
|
+ return processSuccess(MapTools.jacksonObjToStr(tempObject), sql, (Objects.nonNull(batchPm) && batchPm.get(0) != null) ? MapTools.jacksonObjToStr(batchPm) : MapTools.jacksonObjToStr(params));
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("根据条件更新异常,SQL: " + LogUtils.getException(e), sql, ((Objects.nonNull(batchPm) && batchPm.get(0) != null) ? MapTools.jacksonObjToStr(batchPm) : MapTools.jacksonObjToStr(params)));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ public synchronized Boolean updateEvent6Map(String tableName, Object updateParam, boolean isAdd) {
|
|
|
+ boolean isNew = false;
|
|
|
+ if (!event6Map.containsKey(tableName)) {
|
|
|
+ event6Map.put(tableName, new ArrayList<>());
|
|
|
+ }
|
|
|
+ List<Object> tableUniqe = event6Map.get(tableName);
|
|
|
+ if (isAdd) {
|
|
|
+ if (!tableUniqe.contains(updateParam)) {
|
|
|
+ isNew = true;
|
|
|
+ tableUniqe.add(updateParam);
|
|
|
+ }
|
|
|
+ if (tableUniqe.size() > 6000) {
|
|
|
+ tableUniqe.remove(0);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ tableUniqe.remove(updateParam);
|
|
|
+ }
|
|
|
+ return isNew;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Map<String, Object> insertOrUpdate(String tableName, List<Map<String, Object>> paramsList) {
|
|
|
+ List<Map<String, Object>> returnList = new ArrayList<>();
|
|
|
+ for (Map<String, Object> signParam : paramsList) {
|
|
|
+ String eventStr = "2";
|
|
|
+ if (updateEvent6Map(tableName, signParam.get("filter"), true)) {
|
|
|
+ Map<String, Object> selectMap = generalProcess("0", null, "select 1 from " + tableName, null, paramsList, false, 1, 1);
|
|
|
+ if (selectMap.get("code").equals("-1")) {
|
|
|
+ updateEvent6Map(tableName, signParam.get("filter"), false);
|
|
|
+ returnList.add(selectMap);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ eventStr = (Objects.isNull(selectMap.get("returnData")) || ((List<?>) selectMap.get("returnData")).size() == 0) ? "1" : eventStr;
|
|
|
+ }
|
|
|
+
|
|
|
+ returnList.add(generalProcess(eventStr, tableName, null, null, new ArrayList<>() {{
|
|
|
+ add(signParam);
|
|
|
+ }}, false, null, null));
|
|
|
+ }
|
|
|
+ return returnList.size() == 1 ? returnList.get(0) : processSuccess(returnList, tableName, paramsList);
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ public Map<String, Object> generalProcess(String event, String tableName, String sql, String rowCountSQL, List<Map<String, Object>> paramsList, boolean isActive, Object page, Object pageSize) {
|
|
|
+
|
|
|
+ if (MapTools.isBlank(tableName) && MapTools.isBlank(sql)) {
|
|
|
+ return processFail("generalProcess核心入口参数为空 ", null, paramsList);
|
|
|
+ }
|
|
|
+ if (MapTools.isBlank(tableName)) {
|
|
|
+ String tempEvent = AppConfig.staticEvent.get(sql.trim().toLowerCase().substring(0, 6));
|
|
|
+ if (MapTools.isBlank(event)) {
|
|
|
+ event = tempEvent;
|
|
|
+ } else {
|
|
|
+ if (!tempEvent.equals(event)) {
|
|
|
+ return processFail("generalProcess事件标志错误: event与SQL类型不匹配" + event, sql, paramsList);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ List<Object> returnList = new ArrayList<>();
|
|
|
+
|
|
|
+ if (MapTools.isBlank(tableName) && sql.contains("《")) {
|
|
|
+ Map<String, Object> parameterListByBookTitle = getParameterListByBookTitle(sql, paramsList, rowCountSQL);
|
|
|
+ String querySQL = parameterListByBookTitle.get("sql").toString();
|
|
|
+ rowCountSQL = Objects.isNull(parameterListByBookTitle.get("rowCountSQL")) ? null : parameterListByBookTitle.get("rowCountSQL").toString();
|
|
|
+ List<Object[]> sqlValue = Objects.isNull(parameterListByBookTitle.get("value")) ? new ArrayList<>() : (List<Object[]>) parameterListByBookTitle.get("value");
|
|
|
+ return execSign(event, querySQL, rowCountSQL, page, pageSize, sqlValue, paramsList);
|
|
|
+ } else {
|
|
|
+ List<String> allColumn = new ArrayList<>();
|
|
|
+ List<String> allPrimaryKey = new ArrayList<>();
|
|
|
+ if (MapTools.isBlank(tableName)) {
|
|
|
+ if ("0".equals(event)) {
|
|
|
+ Map<String, Object> tempAllColumn = getAllColumnBySql(sql);
|
|
|
+ if (tempAllColumn.get("code").equals("-1")) {
|
|
|
+ return tempAllColumn;
|
|
|
+ }
|
|
|
+ HashMap<String, List<String>> sqlMetaData = (HashMap<String, List<String>>) tempAllColumn.get("returnData");
|
|
|
+ allColumn = sqlMetaData.get("allColumn");
|
|
|
+ List<String> tableNameList = sqlMetaData.get("tableList");
|
|
|
+ if (Objects.nonNull(tableNameList) && tableNameList.size() == 1) {
|
|
|
+ tableName = tableNameList.get(0);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ tableName = getTableBySql(sql);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (!MapTools.isBlank(tableName)) {
|
|
|
+ Map<String, Object> allColumnByTable = getMetaDataByTable(tableName, isActive);
|
|
|
+ if (allColumnByTable.get("code").equals("-1")) {
|
|
|
+ return allColumnByTable;
|
|
|
+ }
|
|
|
+ allColumn = tableColumn.get(tableName);
|
|
|
+ allPrimaryKey = tablePrimaryKey.get(tableName);
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<String, Map<String, Object>> modify = getModify(sql, tableName, paramsList, allColumn, allPrimaryKey, event, isActive, rowCountSQL);
|
|
|
+ for (String sqlStr : modify.keySet()) {
|
|
|
+ if (modify.keySet().size() == 1) {
|
|
|
+ return execSign(event, sqlStr, modify.get(sqlStr).get("rowCountSQL"), page, pageSize, (List<Object[]>) modify.get(sqlStr).get("valueList"), paramsList);
|
|
|
+ } else {
|
|
|
+ Map<String, Object> map = execSign(event, sqlStr, modify.get(sqlStr).get("rowCountSQL"), page, pageSize, (List<Object[]>) modify.get(sqlStr).get("valueList"), paramsList);
|
|
|
+ returnList.add(map.get("returnData"));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return processSuccess(returnList, sql, paramsList);
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> execSign(String event, String sql, Object rowCountSQL, Object page, Object pageSize, List<Object[]> parameterList, List<Map<String, Object>> paramsList) {
|
|
|
+ if ("0".equals(event)) {
|
|
|
+ if (sql.lastIndexOf(")") >= sql.lastIndexOf("limit")) {
|
|
|
+ int thePage = (Objects.isNull(page) || !MapTools.isNumber(page.toString())) ? 1 : Integer.parseInt(page.toString());
|
|
|
+ int thePageSize = (Objects.isNull(pageSize) || !MapTools.isNumber(pageSize.toString())) ? 50 : Integer.parseInt(pageSize.toString());
|
|
|
+ sql = sql + ((thePage == 1 && thePageSize == 1) ? " limit 1 " : (" limit " + ((thePage - 1) * thePageSize) + " ," + thePageSize));
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ Map<String, Object> returnData = processSuccess(theJdbcTemplate.queryForList(sql, parameterList.get(0)), sql, parameterList.get(0));
|
|
|
+ if (Objects.nonNull(rowCountSQL)) {
|
|
|
+ returnData.put("rowcount", theJdbcTemplate.queryForObject(rowCountSQL.toString(), Integer.class, parameterList.get(0)));
|
|
|
+ }
|
|
|
+ return returnData;
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("查询出现异常:" + LogUtils.getException(e), sql, parameterList);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if ("1".equals(event)) {
|
|
|
+ return JDBCBatch(sql, parameterList, paramsList);
|
|
|
+ }
|
|
|
+ return updateByCondition(sql, parameterList);
|
|
|
+ }
|
|
|
+
|
|
|
+ public synchronized Map<String, Object> JDBCBatch(String sql, List<Object[]> paramList, List<Map<String, Object>> paramsList) {
|
|
|
+ if (!sql.contains("?")) {
|
|
|
+ return processSuccess(null, sql, paramsList);
|
|
|
+ }
|
|
|
+ ResultSet currentRS = null;
|
|
|
+ PreparedStatement sqlPS = null;
|
|
|
+ Connection connection = null;
|
|
|
+ try {
|
|
|
+ connection = theDataSource.getConnection();
|
|
|
+ connection.setAutoCommit(false);
|
|
|
+ sqlPS = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+ for (Object[] list : paramList) {
|
|
|
+ for (int j = 0; j < list.length; j++) {
|
|
|
+ sqlPS.setObject(j + 1, list[j]);
|
|
|
+ }
|
|
|
+ sqlPS.addBatch();
|
|
|
+ }
|
|
|
+ sqlPS.executeBatch();
|
|
|
+ connection.commit();
|
|
|
+ List<String> currentPRIKeyList = tablePrimaryKey.get(getTableBySql(sql));
|
|
|
+ if (Objects.nonNull(currentPRIKeyList) && currentPRIKeyList.size() > 0) {
|
|
|
+ currentRS = sqlPS.getGeneratedKeys();
|
|
|
+ int index = 0;
|
|
|
+ while (currentRS.next()) {
|
|
|
+ int keyIndex = 1;
|
|
|
+ for (String priKey : currentPRIKeyList) {
|
|
|
+ Map<String, Object> indexMap = paramsList.get(index);
|
|
|
+ if (indexMap.containsKey("Value") && indexMap.get("Value") instanceof Map<?, ?>) {
|
|
|
+ indexMap = (Map<String, Object>) indexMap.get("Value");
|
|
|
+ }
|
|
|
+ indexMap.put(priKey, currentRS.getObject(keyIndex));
|
|
|
+ paramsList.set(index, indexMap);
|
|
|
+ keyIndex++;
|
|
|
+ }
|
|
|
+ index++;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return processSuccess(paramsList, sql, paramList);
|
|
|
+ } catch (Exception e) {
|
|
|
+ try {
|
|
|
+ if (connection != null) {
|
|
|
+ connection.rollback();
|
|
|
+ }
|
|
|
+ } catch (SQLException ex) {
|
|
|
+ System.out.println("jdbc 批量新增 : 事务回滚异常信息:" + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ return processFail("dbSava执行批量Insert SQL异常 " + LogUtils.getException(e) + "事务回滚", sql, paramList);
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ if (currentRS != null) {
|
|
|
+ currentRS.close();
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ System.out.println("jdbc 批量新增 关闭结果集异常: " + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ if (sqlPS != null) {
|
|
|
+ sqlPS.close();
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ System.out.println("jdbc 批量新增 关闭预编译异常: " + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ if (connection != null) {
|
|
|
+ connection.setAutoCommit(true);
|
|
|
+ connection.close();
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ System.out.println("jdbc 批量新增 关闭连接异常: " + LogUtils.getException(e));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Map<String, Object>> getModify(String sql, String tableName, List<Map<String, Object>> paramsList, List<String> allColumn, List<String> allPrimaryKey, String event, boolean isActive, String rowCountSQL) {
|
|
|
+
|
|
|
+ if (Objects.isNull(allColumn)) allColumn = new ArrayList<>();
|
|
|
+ if (Objects.isNull(allPrimaryKey)) allPrimaryKey = new ArrayList<>();
|
|
|
+
|
|
|
+ if (isActive && event.equals("1")) {
|
|
|
+ for (Map<String, Object> itemMap : paramsList) {
|
|
|
+ Map<String, Object> valueMap = itemMap.containsKey("Value") ? (Map<String, Object>) itemMap.get("Value") : itemMap;
|
|
|
+ for (String key : valueMap.keySet()) {
|
|
|
+ if (!allColumn.contains(key) && !allPrimaryKey.contains(key)) {
|
|
|
+ theJdbcTemplate.execute("alter table " + tableName + " add " + key + " text ");
|
|
|
+ allColumn.add(key);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ allColumn.removeAll(allPrimaryKey);
|
|
|
+ Map<String, Map<String, Object>> sqlMap = new HashMap<>();
|
|
|
+ if ("0".contains(event) && paramsList.size() > 1) {
|
|
|
+ List<Map<String, Object>> tempList = new ArrayList<>();
|
|
|
+ tempList.add(paramsList.get(0));
|
|
|
+ paramsList = tempList;
|
|
|
+ }
|
|
|
+ for (Map<String, Object> itemMap : paramsList) {
|
|
|
+ List<Object> cuList = new ArrayList<>();
|
|
|
+ List<String> modifyCol = new ArrayList<>();
|
|
|
+ List<String> modifyValue = new ArrayList<>();
|
|
|
+ if ("1,2".contains(event)) {
|
|
|
+ Map<String, Object> valueMap = itemMap.containsKey("Value") ? (Map<String, Object>) itemMap.get("Value") : itemMap;
|
|
|
+ if (allColumn.contains("createtime")) {
|
|
|
+ valueMap.put("createtime", new Date());
|
|
|
+ }
|
|
|
+ if (event.equals("1")) {
|
|
|
+ for (String column : allColumn) {
|
|
|
+ cuList.add(valueMap.get(column));
|
|
|
+ modifyValue.add("?");
|
|
|
+ }
|
|
|
+ modifyCol = allColumn;
|
|
|
+ } else {
|
|
|
+ for (String key : valueMap.keySet()) {
|
|
|
+ cuList.add(valueMap.get(key));
|
|
|
+ modifyCol.add(key + "=?");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ String whereStr = "";
|
|
|
+ if (!event.equals("1")) {
|
|
|
+ List<Map<String, Object>> filterMapList = new ArrayList<>();
|
|
|
+ Object tempObj = itemMap.get("filter");
|
|
|
+ if (tempObj instanceof Map || tempObj instanceof List) {
|
|
|
+ if (tempObj instanceof Map) {
|
|
|
+ if (((Map<String, Object>) tempObj).containsKey("left")) {
|
|
|
+ filterMapList.add((Map<String, Object>) tempObj);
|
|
|
+ } else {
|
|
|
+ authoParams((Map<String, Object>) tempObj, filterMapList, allColumn, allPrimaryKey);
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ if (((List<?>) tempObj).size() > 0) {
|
|
|
+ Object firstObj = ((List<?>) tempObj).get(0);
|
|
|
+ if (firstObj instanceof Map<?, ?>) {
|
|
|
+ if (((Map<?, ?>) firstObj).containsKey("left")) {
|
|
|
+ filterMapList = (List<Map<String, Object>>) tempObj;
|
|
|
+ } else {
|
|
|
+ authoParams((Map<String, Object>) firstObj, filterMapList, allColumn, allPrimaryKey);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ authoParams(itemMap, filterMapList, allColumn, allPrimaryKey);
|
|
|
+ }
|
|
|
+ List<Map<String, Object>> prikeyFilter = new ArrayList<>();
|
|
|
+ List<String> prikeyCount = new ArrayList<>();
|
|
|
+ for (Map<String, Object> filterMap : filterMapList) {
|
|
|
+ if (filterMap.containsKey("column") && allPrimaryKey.contains(filterMap.get("column").toString())) {
|
|
|
+ if (!prikeyCount.contains(filterMap.get("column").toString())) {
|
|
|
+ prikeyCount.add(filterMap.get("column").toString());
|
|
|
+ }
|
|
|
+ prikeyFilter.add(filterMap);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (prikeyFilter.size() > 0 && prikeyCount.size() == allPrimaryKey.size()) {
|
|
|
+ filterMapList = prikeyFilter;
|
|
|
+ }
|
|
|
+ for (Map<String, Object> filter : filterMapList) {
|
|
|
+ whereStr = whereStr.concat(filter.get("left").toString()).concat(filter.get("column").toString()).concat(filter.get("comparator").toString()).concat(filter.get("comparator").equals(" is null ") ? "" : "?").concat(filter.get("right").toString())
|
|
|
+ .concat((Objects.isNull(filter.get("connector")) || filter.get("connector").toString().trim().equals("")) ? " and " : " " + filter.get("connector").toString().trim() + " ");
|
|
|
+ if (!filter.get("comparator").equals(" is null ")) {
|
|
|
+ cuList.add(filter.get("value"));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ whereStr = whereStr.trim();
|
|
|
+ whereStr = whereStr.endsWith("and") || whereStr.endsWith(" or") ? whereStr.substring(0, whereStr.length() - 3) : whereStr;
|
|
|
+ }
|
|
|
+ String sqlStr = !MapTools.isBlank(sql) ? sql : eventSQL.get(event).replace("表名", tableName).replace("字段", String.join(",", modifyCol)).replace("值", String.join(",", modifyValue));
|
|
|
+ if (event.equals("0") && !MapTools.isBlank(tableName)) {
|
|
|
+ rowCountSQL = "select count(1) from " + tableName;
|
|
|
+ }
|
|
|
+ if (event.equals("0") && MapTools.isNotBlank(sql) && MapTools.isBlank(rowCountSQL) && allColumn.size() > 0) {
|
|
|
+ rowCountSQL = sql;
|
|
|
+ for (int index = 0; index < allColumn.size(); index++) {
|
|
|
+ rowCountSQL = rowCountSQL.replace(allColumn.get(index), index == 0 ? " count(1) " : "");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (!event.equals("1") && !whereStr.equals("")) {
|
|
|
+ sqlStr = sqlStr.concat(sqlStr.lastIndexOf(")") >= sqlStr.lastIndexOf(" where ") ? " where " : " and ").concat("(").concat(whereStr).concat(" )");
|
|
|
+ if (!MapTools.isBlank(rowCountSQL)) {
|
|
|
+ rowCountSQL = rowCountSQL.concat(sqlStr.lastIndexOf(")") >= sqlStr.lastIndexOf(" where ") ? " where " : " and ").concat("(").concat(whereStr).concat(")");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Map<String, Object> sqlMapValue = sqlMap.get(sqlStr);
|
|
|
+ if (Objects.isNull(sqlMapValue) || sqlMapValue.isEmpty()) {
|
|
|
+ sqlMapValue = new HashMap<>();
|
|
|
+ List<Object> vaList = new ArrayList<>();
|
|
|
+ vaList.add(cuList.toArray());
|
|
|
+ sqlMapValue.put("valueList", vaList);
|
|
|
+ sqlMapValue.put("rowCountSQL", rowCountSQL);
|
|
|
+ } else {
|
|
|
+ List<Object> valueList = (List<Object>) sqlMapValue.get("valueList");
|
|
|
+ valueList.add(cuList.toArray());
|
|
|
+ sqlMapValue.put("valueList", valueList);
|
|
|
+
|
|
|
+ }
|
|
|
+ sqlMap.put(sqlStr, sqlMapValue);
|
|
|
+ }
|
|
|
+ return sqlMap;
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ private void authoParams(Map<String, Object> itemMap, List<Map<String, Object>> filterMapList, List<String> allColumn, List<String> allPrimaryKey) {
|
|
|
+ itemMap = Objects.isNull(itemMap) ? new HashMap<>() : itemMap;
|
|
|
+ for (String filterKey : itemMap.keySet()) {
|
|
|
+ if (!allColumn.contains(filterKey) && !allPrimaryKey.contains(filterKey)) continue;
|
|
|
+ HashMap<String, Object> filterMap = new HashMap<>();
|
|
|
+ Object keyValues = itemMap.get(filterKey);
|
|
|
+ filterMap.put("left", "");
|
|
|
+ filterMap.put("column", filterKey);
|
|
|
+ filterMap.put("comparator", " = ");
|
|
|
+ if (Objects.isNull(keyValues)) {
|
|
|
+ filterMap.put("comparator", " is null ");
|
|
|
+ }
|
|
|
+ filterMap.put("value", keyValues);
|
|
|
+ filterMap.put("right", "");
|
|
|
+ filterMap.put("connector", " and ");
|
|
|
+ filterMapList.add(filterMap);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> getMetaDataByTable(String tableName, boolean isActive) {
|
|
|
+ if (!MapTools.isBlank(tableName) && !tableList.contains(tableName)) {
|
|
|
+ if (isActive) {
|
|
|
+ try {
|
|
|
+ String tempSql = "CREATE TABLE if not EXISTS " + tableName + " (" + tableName + "_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,`dataObjectId` VARCHAR(32) DEFAULT NULL ,`createtime` datetime ) ";
|
|
|
+ theJdbcTemplate.execute(tempSql);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("动态创建表时异常:" + LogUtils.getException(e), tableName, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ } else {
|
|
|
+ return processFail("表名为空或者当前数据库中不存在此表", tableName, null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (!(tableColumn.containsKey(tableName))) {
|
|
|
+ Connection connection = null;
|
|
|
+ ResultSet columnRsesult = null;
|
|
|
+ try {
|
|
|
+ connection = theDataSource.getConnection();
|
|
|
+ DatabaseMetaData tempMetaData = connection.getMetaData();
|
|
|
+ columnRsesult = tempMetaData.getColumns(connection.getCatalog(), connection.getCatalog(), tableName, null);
|
|
|
+ List<String> columnList = new ArrayList<>();
|
|
|
+ while (columnRsesult.next()) {
|
|
|
+ columnList.add(columnRsesult.getString("COLUMN_NAME"));
|
|
|
+ }
|
|
|
+ tableColumn.put(tableName, columnList);
|
|
|
+
|
|
|
+
|
|
|
+ ResultSet primaryKeyResult = tempMetaData.getPrimaryKeys(connection.getCatalog(), connection.getCatalog(), tableName);
|
|
|
+ List<String> primaryKeyList = new ArrayList<>();
|
|
|
+ while (primaryKeyResult.next()) {
|
|
|
+ String priKeyName = primaryKeyResult.getString("COLUMN_NAME");
|
|
|
+ if (!primaryKeyList.contains(priKeyName)) {
|
|
|
+ primaryKeyList.add(priKeyName);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ tablePrimaryKey.put(tableName, primaryKeyList);
|
|
|
+
|
|
|
+
|
|
|
+ } catch (Exception e) {
|
|
|
+ return processFail("获取表的所有列异常:" + LogUtils.getException(e), tableName, null);
|
|
|
+ } finally {
|
|
|
+ if (columnRsesult != null) {
|
|
|
+ try {
|
|
|
+ columnRsesult.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭结果集异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (connection != null) {
|
|
|
+ try {
|
|
|
+ connection.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭连接异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ return processSuccess(null, tableName, null);
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * 根据sql获取表名
|
|
|
+ *
|
|
|
+ * @param sql
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ private String getTableBySql(String sql) {
|
|
|
+ String[] sqlSplit = sql.trim().toLowerCase().split("\\s+");
|
|
|
+ if (sqlSplit[0].equals("insert")) {
|
|
|
+ String tableName = sqlSplit[2];
|
|
|
+ tableName = tableName.indexOf("(") > 0 ? tableName.substring(0, tableName.indexOf("(")) : tableName;
|
|
|
+ return tableName;
|
|
|
+ }
|
|
|
+ if (sqlSplit[0].equals("update")) {
|
|
|
+ return sqlSplit[1];
|
|
|
+ }
|
|
|
+ if (sqlSplit[0].equals("delete")) {
|
|
|
+ return sqlSplit[2];
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Map<String, Object> getAllColumnBySql(String sql) {
|
|
|
+ if (sql.lastIndexOf(")") >= sql.lastIndexOf("limit")) {
|
|
|
+ sql = sql + " limit 1";
|
|
|
+ }
|
|
|
+ if (!sqlColumn.containsKey(sql)) {
|
|
|
+ ResultSet rs = null;
|
|
|
+ Connection connection = null;
|
|
|
+ PreparedStatement ps = null;
|
|
|
+ try {
|
|
|
+ connection = theDataSource.getConnection();
|
|
|
+ ps = connection.prepareStatement(sql);
|
|
|
+ rs = ps.executeQuery();
|
|
|
+ ResultSetMetaData rsd = rs.getMetaData();
|
|
|
+ List<String> allColumn = new ArrayList<>();
|
|
|
+ List<String> tableList = new ArrayList<>();
|
|
|
+ for (int i = 0; i < rsd.getColumnCount(); i++) {
|
|
|
+ allColumn.add(rsd.getColumnName(i + 1));
|
|
|
+ String tableName = rsd.getTableName(i + 1);
|
|
|
+ if (!tableList.contains(tableName)) {
|
|
|
+ tableList.add(tableName);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ HashMap<String, List<String>> sqlMeta = new HashMap<>();
|
|
|
+ sqlMeta.put("allColumn", allColumn);
|
|
|
+ sqlMeta.put("tableList", tableList);
|
|
|
+ sqlColumn.put(sql, sqlMeta);
|
|
|
+ } catch (SQLException e) {
|
|
|
+ return processFail("getAllColumnBySql 异常: " + LogUtils.getException(e), sql, null);
|
|
|
+ } finally {
|
|
|
+ if (rs != null) {
|
|
|
+ try {
|
|
|
+ rs.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭结果集异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (ps != null) {
|
|
|
+ try {
|
|
|
+ ps.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭预编译异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (connection != null) {
|
|
|
+ try {
|
|
|
+ connection.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭连接异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return processSuccess(sqlColumn.get(sql), sql, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ public Map<String, Object> getAllColumnForSet(String sql) {
|
|
|
+ if (sql.lastIndexOf(")") >= sql.lastIndexOf("limit")) {
|
|
|
+ sql = sql + " limit 1";
|
|
|
+ }
|
|
|
+ ResultSet rs = null;
|
|
|
+ Connection connection = null;
|
|
|
+ PreparedStatement ps = null;
|
|
|
+ try {
|
|
|
+ connection = theDataSource.getConnection();
|
|
|
+ ps = connection.prepareStatement(sql);
|
|
|
+ rs = ps.executeQuery();
|
|
|
+ ResultSetMetaData rsd = rs.getMetaData();
|
|
|
+ List<Map<String, Object>> allColumnList = new ArrayList<>();
|
|
|
+ for (int i = 0; i < rsd.getColumnCount(); i++) {
|
|
|
+ HashMap<String, Object> tempMap = new HashMap<>();
|
|
|
+ tempMap.put("columnName", rsd.getColumnName(i + 1));
|
|
|
+ tempMap.put("columnType", rsd.getColumnType(i + 1));
|
|
|
+ tempMap.put("columnTypeName", rsd.getColumnTypeName(i + 1));
|
|
|
+ tempMap.put("columnLable", rsd.getColumnLabel(i + 1));
|
|
|
+ allColumnList.add(tempMap);
|
|
|
+ }
|
|
|
+ return processSuccess(allColumnList, sql, null);
|
|
|
+ } catch (SQLException e) {
|
|
|
+ return processFail("getAllColumnForSet 异常: " + LogUtils.getException(e), sql, null);
|
|
|
+ } finally {
|
|
|
+ if (rs != null) {
|
|
|
+ try {
|
|
|
+ rs.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭结果集异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (ps != null) {
|
|
|
+ try {
|
|
|
+ ps.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭预编译异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (connection != null) {
|
|
|
+ try {
|
|
|
+ connection.close();
|
|
|
+ } catch (SQLException sqle) {
|
|
|
+ System.out.println("获取所有列,关闭连接异常");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> getParameterListByBookTitle(String sql, List<Map<String, Object>> paramsList, String rowCountSQL) {
|
|
|
+ List<Object[]> returnData = new ArrayList<>();
|
|
|
+ Pattern regExpression = Pattern.compile("(?<=《)([^》]+)?(?=》)");
|
|
|
+ Matcher parameterNames = regExpression.matcher(sql);
|
|
|
+ if ((sql.toLowerCase().trim().startsWith("select") || sql.toLowerCase().trim().startsWith("delete")) && paramsList.size() > 1) {
|
|
|
+ Map<String, Object> temMap = paramsList.get(0);
|
|
|
+ paramsList = new ArrayList<>() {
|
|
|
+ {
|
|
|
+ add(temMap);
|
|
|
+ }
|
|
|
+ };
|
|
|
+ }
|
|
|
+ List<Object> signList = new ArrayList<>();
|
|
|
+ List<String> columnName = new ArrayList<>();
|
|
|
+ while (parameterNames.find()) {
|
|
|
+ String colName = parameterNames.group();
|
|
|
+ columnName.add(colName);
|
|
|
+ signList.add(null);
|
|
|
+ sql = sql.replaceFirst("《" + colName + "》", "?");
|
|
|
+ if (Objects.nonNull(rowCountSQL)) {
|
|
|
+ rowCountSQL = rowCountSQL.replaceFirst("《" + colName + "》", "?");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ for (Map<String, Object> itemMap : paramsList) {
|
|
|
+ int paramIndex = 0;
|
|
|
+ for (String colName : columnName) {
|
|
|
+ signList.set(paramIndex, getValue(itemMap, colName));
|
|
|
+ paramIndex++;
|
|
|
+ }
|
|
|
+ returnData.add(signList.toArray());
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ HashMap<String, Object> objectHashMap = new HashMap<>();
|
|
|
+ objectHashMap.put("value", returnData);
|
|
|
+ objectHashMap.put("rowCountSQL", rowCountSQL);
|
|
|
+ objectHashMap.put("sql", sql);
|
|
|
+ return objectHashMap;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Object getValue(Map<?, ?> itemMap, Object itemKey) {
|
|
|
+ if (itemMap.containsKey(itemKey)) return itemMap.get(itemKey);
|
|
|
+ for (Object key : itemMap.keySet()) {
|
|
|
+ Object currentValue = itemMap.get(key);
|
|
|
+ if (currentValue instanceof Map<?, ?> currentMap) {
|
|
|
+ if (currentMap.containsKey("left")) {
|
|
|
+ Object column = currentMap.get("column");
|
|
|
+ if (key.equals(column)) {
|
|
|
+ return currentMap.get("value");
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ return getValue(currentMap, key);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (currentValue instanceof List<?> valueList) {
|
|
|
+ for (Object value : valueList) {
|
|
|
+ if (value instanceof Map<?, ?> valueMap) {
|
|
|
+ Object va = getValue(valueMap, key);
|
|
|
+ if (Objects.nonNull(va)) {
|
|
|
+ return va;
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * 查询数据库条数
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public Map<String, String> queryForObject(String sql, Object... params) {
|
|
|
+ try {
|
|
|
+ Integer count = theJdbcTemplate.queryForObject(sql, Integer.class, params);
|
|
|
+ HashMap<String, String> tempMap = new HashMap<>();
|
|
|
+ tempMap.put("code", "0");
|
|
|
+ tempMap.put("returnData", count + "");
|
|
|
+ return tempMap;
|
|
|
+ } catch (Exception e) {
|
|
|
+ HashMap<String, String> tempMap = new HashMap<>();
|
|
|
+ tempMap.put("code", "-1");
|
|
|
+ tempMap.put("message", "查询条数 执行异常: " + LogUtils.getException(e));
|
|
|
+ return tempMap;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ * jdbcTemplate 插入数据后返回,主键的值
|
|
|
+ * @param sql sql语句
|
|
|
+ * @param params sql参数
|
|
|
+ * @return 插入的主键ID
|
|
|
+ */
|
|
|
+ public Map<String, Object> insertReturnKeyValues(String sql, Object... params) {
|
|
|
+ try {
|
|
|
+ KeyHolder holder = new GeneratedKeyHolder();
|
|
|
+ theJdbcTemplate.update(connection -> {
|
|
|
+ PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
|
|
|
+ for (Object param : params) {
|
|
|
+ ps.setObject(1, param);
|
|
|
+ }
|
|
|
+ return ps;
|
|
|
+ }, holder);
|
|
|
+ HashMap<String, Object> tempMap = new HashMap<>();
|
|
|
+ tempMap.put("code", "0");
|
|
|
+ tempMap.put("returnData", Objects.requireNonNull(holder.getKey()).intValue());
|
|
|
+ return tempMap;
|
|
|
+ } catch (Exception e) {
|
|
|
+ HashMap<String, Object> tempMap = new HashMap<>();
|
|
|
+ tempMap.put("code", "-1");
|
|
|
+ tempMap.put("message", LogUtils.getException(e));
|
|
|
+ return tempMap;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public String getErrorMessage() {
|
|
|
+ return errorMessage;
|
|
|
+ }
|
|
|
+
|
|
|
+ public String getConnectConfig() {
|
|
|
+ return connectConfig;
|
|
|
+ }
|
|
|
+
|
|
|
+ public HikariDataSource getTheDataSource() {
|
|
|
+ return theDataSource;
|
|
|
+ }
|
|
|
+
|
|
|
+ public JdbcTemplate getTheJdbcTemplate() {
|
|
|
+ return theJdbcTemplate;
|
|
|
+ }
|
|
|
+
|
|
|
+}
|