ludc
2023-11-17 ac8e8998235f247365280d1a1632115c43b10037
Source/UBCS/ubcs-service/ubcs-code/src/main/java/com/vci/ubcs/code/service/impl/MdmEngineServiceImpl.java
@@ -69,7 +69,11 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
@@ -99,10 +103,22 @@
public class MdmEngineServiceImpl implements MdmEngineService {
   /**
    * 多线程方式批量执行开启线程池的总数
    */
   @Value("${batchadd.thread_num:10}")
   private Integer THREAD_NUM;
   /**
    * 单次sql的最多导入数量
    */
   @Value("${import.maxNum}")
   @Value("${batchadd.single_maxnum:200}")
   private Integer MAX_IMPORT_NUM;
   /**
    * 是否开启多线程方式导入历史数据
    */
   @Value("${batchadd.is_thread_import:false}")
   private boolean IS_THREAD_IMPORT;
    /**
     * 模板的服务
@@ -153,13 +169,11 @@
    @Autowired
    private FormulaServiceImpl formulaService;
    /**
     * 对omd中提供的feign接口进行调用,以及处理相关逻辑
     */
    @Autowired
    ICodeReferBtmTypeService codeReferBtmTypeService;
    /**
     * 相似项查询规则
@@ -417,7 +431,7 @@
     * @param orderDTO 申请的信息,需要包含属性的内容和码段相关的内容
     * @return 返回编码的内容
     */
    private String addSaveCode(CodeOrderDTO orderDTO,boolean authUser) throws Exception {
   private String addSaveCode(CodeOrderDTO orderDTO, boolean authUser) throws Exception {
        VciBaseUtil.alertNotNull(orderDTO, "编码申请相关的属性和码段的内容都为空", orderDTO.getCodeClassifyOid(), "主题库分类的主键",
                orderDTO.getTemplateOid(), "模板的主键", orderDTO.getCodeRuleOid(), "编码规则的主键");
        CodeClassifyFullInfoBO classifyFullInfo = classifyService.getClassifyFullInfo(orderDTO.getCodeClassifyOid());
@@ -687,14 +701,16 @@
        //没有限制分类,但是一个模板只可能在一个业务类型里面,所以直接查询这个业务类型即可
        if (!CollectionUtils.isEmpty(conditionMap)) {
         conditionMap.put("CODETEMPLATEOID","'" + orderDTO.getTemplateOid() + "'");
         // TODO: 同一个库判重不需要区分分类oid
         // conditionMap.put("CODETEMPLATEOID","'" + orderDTO.getTemplateOid() + "'");
//         final String[] sql = {"select count(*) from " + VciBaseUtil.getTableName(classifyFullInfo.getTopClassifyVO().getBtmtypeid()) + " t where 1 = 1 "};
            R<List<BtmTypeVO>> listR = btmTypeClient.selectByIdCollection(Collections.singletonList(classifyFullInfo.getTopClassifyVO().getBtmTypeId()));
//            String referTable = VciBaseUtil.getTableName(referVO.getReferType());
            if (!listR.isSuccess() || listR.getData().size() == 0) {
                throw new VciBaseException("传入业务类型未查询到相应表单,请检查!");
            }
            final String[] sql = {"select count(*) from " + listR.getData().get(0).getTableName() + " t where 1 = 1 "};
            //final String[] sql = {"select count(*) from " + listR.getData().get(0).getTableName() + " t where 1 = 1 "};
         final String[] sql = {"select id from " + listR.getData().get(0).getTableName() + " t where 1 = 1 "};
            conditionMap.forEach((key, value) -> {
            if(StringUtils.isBlank(value)||value.equals(QueryOptionConstant.ISNULL)) {
               sql[0] += " and " + key + " is null";
@@ -709,11 +725,16 @@
                sql[0] += " and oid != '" + orderDTO.getCopyFromVersion() + "'";
            }
            sql[0] += " and lastR = '1' and lastV = '1' ";
         String isParticipateCheckOids = classifyService.selectLeafByParentClassifyOid(classifyFullInfo.getTopClassifyVO().getOid(), classifyFullInfo.getCurrentClassifyVO().getOid());
         if(Func.isNotEmpty(isParticipateCheckOids)){
            sql[0] += " and codeclsfid not in(" + isParticipateCheckOids + ")";
         }
//         if (boService.queryCountBySql(sql[0], new HashMap<>()) > 0) {
            if (Integer.parseInt(commonsMapper.selectById(sql[0]).get(0)) > 0) {
         List<String> repeatData = commonsMapper.selectList(sql[0]);
         if (!repeatData.isEmpty()) {
                String ruleInfoMsg = keyRuleVO == null ? "" : "查询规则:去除空格--{0},忽略大小写--{1},忽略全半角--{2},忽略全部空格--{3}";
                String[] objs = new String[]{trim ? "是" : "否", ignoreCase ? "是" : "否", ignoreWidth ? "是" : "否", trimAll ? "是" : "否"};
                throw new VciBaseException("根据您填写的关键属性的内容,结合关键属性查询规则,发现这个数据已经在系统中存在了。请修正!。" + ruleInfoMsg, objs);
                throw new VciBaseException("根据您填写的关键属性的内容,结合关键属性查询规则,发现该数据已经与系统中编号为"+repeatData.stream().collect(Collectors.joining(","))+"的数据重复。请修正!。" + ruleInfoMsg, objs);
            }
        }
    }
@@ -962,10 +983,10 @@
//                  cbo.setLcStatus("Editing");
////                  cbo.setLcStatus(lifeCycleVO.getStartStatus());
//               } else {
                    cbo.setLcStatus(CodeDefaultLC.EDITING.getValue());
                    cbo.setLcStatus(CodeDefaultLC.RELEASED.getValue());
//               }
                } else {
                    cbo.setLcStatus(CodeDefaultLC.EDITING.getValue());
                    cbo.setLcStatus(CodeDefaultLC.RELEASED.getValue());
                }
            }
@@ -980,7 +1001,6 @@
            logger.error("设置默认的属性的值错误", e);
        }
    }
    /**
     * 初始化业务类型
@@ -1780,7 +1800,6 @@
        }
    }
    /**
     * 根据模板属性生成相应的sql信息
     *
@@ -1946,6 +1965,8 @@
        String sqlHasPage = pageHelper.getLimit() > 0 ? ("select * from (select A.*,rownum RN from (" + sql + whereSubfixForPage) : sql;
        String sqlCount = "select count(1) from " + tableName + SPACE + "t" + SPACE + joinTableList.values().stream().collect(Collectors.joining(SPACE))
                + (StringUtils.isBlank(whereSql) ? "" : " where ") + whereSql;
      String sqlId = "select ID from " + tableName + SPACE + "t" + SPACE + joinTableList.values().stream().collect(Collectors.joining(SPACE))
         + (StringUtils.isBlank(whereSql) ? "" : " where ") + whereSql;
        CodeTemplateAttrSqlBO sqlBO = new CodeTemplateAttrSqlBO();
        sqlBO.setTableName(tableName);
        sqlBO.setJoinTable(joinTableList);
@@ -1954,9 +1975,9 @@
        sqlBO.setSqlHasPage(sqlHasPage);
        sqlBO.setSqlCount(sqlCount);
        sqlBO.setSqlUnPage(sql);
      sqlBO.setSqlId(sqlId);
        return sqlBO;
    }
    /**
     * 组合查询条件的sql
@@ -2760,6 +2781,7 @@
        cbo.setName(orderDTO.getName());
        //数据的时候,编码是不变的
        cbo.setCreateTime(cbo.getCreateTime());
      cbo.setCreator(cbo.getCreator());
        cbo.setLastModifyTime(cbo.getLastModifyTime());
      cbo.setTenantId(AuthUtil.getTenantId());
      oldCbo.setLastV("0");
@@ -3530,7 +3552,6 @@
     * @return 处理成功数据条数
     */
    @Override
   @Transactional(rollbackFor = Exception.class)
    public Integer insertBatchByType(String btmType, List<BaseModel> baseModels) {
        //使用传入的业务类型查询表
        R<List<BtmTypeVO>> listR = btmTypeClient.selectByIdCollection(Collections.singletonList(btmType));
@@ -3555,34 +3576,44 @@
                throw new VciBaseException("类型转换错误:" + e.toString());
            }
        });
      try {
         bactchExecuteInsert(listR.getData().get(0).getTableName(),maps);
      }catch (Exception e){
         throw new ServiceException("分批执行insert语句报错:"+e.getMessage());
      // 是否开启多线程执行插入语句
      if(IS_THREAD_IMPORT){
         try {
            threadBactchExecuteInsert(listR.getData().get(0).getTableName(),maps);
         }catch (Exception e){
            throw new ServiceException("分批执行insert语句报错:"+e.getMessage());
         }
      }else {
         bacthExcecuteInsert(listR.getData().get(0).getTableName(),maps);
      }
        return maps.size();
    }
   /**
    * 分批执行insert语句
    * 多线程方式分批执行insert语句
    * @param tableName
    * @param maps
    * @throws ServiceException
    */
   @Transactional(rollbackFor = Exception.class)
   void bactchExecuteInsert(String tableName, List<Map<String, String>> maps) throws ServiceException{
      ExecutorService executor = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池
   private void threadBactchExecuteInsert(String tableName, List<Map<String, String>> maps) throws ServiceException{
      ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUM); // 创建一个固定大小的线程池
      List<Map<String, String>> threadSafeMaps = new CopyOnWriteArrayList<>(maps);
      for (int i = 0; i < threadSafeMaps.size(); i += MAX_IMPORT_NUM) {
         final int startIndex = i;
         final int endIndex = Math.min(i + MAX_IMPORT_NUM, maps.size());
         executor.execute(() -> {
            List<Map<String, String>> subList = threadSafeMaps.subList(startIndex, endIndex);
            // 调用插入数据库的方法
            commonsMapper.insertByBaseModel(tableName, threadSafeMaps.get(0), subList);
         });
         final int endIndex = Math.min(i + MAX_IMPORT_NUM, threadSafeMaps.size());
         try {
            executor.execute(() -> {
               List<Map<String, String>> subList = threadSafeMaps.subList(startIndex, endIndex);
               // 调用插入数据库的方法
               commonsMapper.insertByBaseModel(tableName, threadSafeMaps.get(0), subList);
            });
         }catch (Throwable e){
            throw new ServiceException(e.getMessage());
         }
      }
      // 关闭线程池
      executor.shutdown();
      try {
@@ -3591,6 +3622,21 @@
      } catch (InterruptedException e) {
         // 处理异常
         throw new ServiceException("多线程方式执行批量插入时产生错误:"+e.getMessage());
      }
   }
   /**
    * 单线程方式分批执行
    * @param tableName
    * @param maps
    */
   private void bacthExcecuteInsert(String tableName, List<Map<String, String>> maps){
      for (int i = 0; i < maps.size(); i += MAX_IMPORT_NUM) {
         final int startIndex = i;
         final int endIndex = Math.min(i + MAX_IMPORT_NUM, maps.size());
         List<Map<String, String>> subList = maps.subList(startIndex, endIndex);
         // 调用插入数据库的方法
         commonsMapper.insertByBaseModel(tableName, maps.get(0), subList);
      }
   }
@@ -4153,7 +4199,7 @@
        toBo.setLastV(String.valueOf(1));
      // 数据升版不需要重新设置创建人,只对最后修改人做更新就可以了
        //toBo.setCreator(String.valueOf(AuthUtil.getUser().getUserId()));
        toBo.setCreateTime(new Date());
        toBo.setCreateTime(fromBo.getCreateTime());
        // toBo.setLastModifier(String.valueOf(AuthUtil.getUser().getUserId()));
      toBo.setLastModifier(String.valueOf(AuthUtil.getUser().getAccount()));
        toBo.setLastModifyTime(new Date());