刘小明
2024-06-19 cfa51be0ceb9a04a1e20b4fba3b4f897c60b611b
pms-parent/pms-web-platform/src/main/java/com/dy/pmsPlatform/station/StationSv.java
@@ -1,6 +1,7 @@
package com.dy.pmsPlatform.station;
import cn.hutool.core.codec.Base64;
import com.alibaba.excel.util.StringUtils;
import com.dy.common.webUtil.QueryResultVo;
import com.dy.pmsGlobal.daoPlt.PltStationMapper;
import com.dy.pmsGlobal.pojoPlt.PltProduct;
@@ -10,6 +11,7 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.PojoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -23,6 +25,8 @@
    private PltStationMapper dao;
    private static final String stationPrefix = "103" ;
    private static final String DEFAULT_CODE = "0001";
    private static final String CODE_FORMAT = "%04d";
    @Autowired
    public void setDao(PltStationMapper dao) {
@@ -31,11 +35,40 @@
    @Transactional
    public int save(PltStation station) throws RuntimeException {
        if(dao.selectByCodeId(station.id,station.code)>0){
            throw new RuntimeException("工站编号已存在");
        }
        int count = dao.insertSelective(station);
//        if(dao.selectByCodeId(station.id,station.code)>0){
//            throw new RuntimeException("工站编号已存在");
//        }
        int count = 0;
        int flag=0;
        do {
            station.code = getNextCode();
            try {
                count = dao.insertSelective(station);
                return count;
            } catch (DuplicateKeyException e) {
                // 如果出现唯一约束违反异常,尝试获取新的code并重试
                log.warn("插入工站时遇到唯一约束异常,尝试获取新的code", e);
            }
            flag++;
        } while (flag<5);
        return count;
    }
    private String getNextCode(){
        log.info("获取工站编号");
        String maxCode = dao.selectMaxCode();
        if (StringUtils.isBlank(maxCode)) {
            return DEFAULT_CODE;
        } else {
            int nextCode = Integer.parseInt(maxCode) + 1;
            // 检查溢出
            if (nextCode > 9999) {
                throw new RuntimeException("工站编号溢出");
            }
            return String.format(CODE_FORMAT, nextCode);
        }
    }
    /**
@@ -52,9 +85,9 @@
    @Transactional
    public int update(PltStation station) throws RuntimeException {
        if(dao.selectByCodeId(station.id,station.code)>0){
            throw new RuntimeException("工站编号已存在");
        }
//        if(dao.selectByCodeId(station.id,station.code)>0){
//            throw new RuntimeException("工站编号已存在");
//        }
        int count = dao.updateByPrimaryKeySelective(station);
        return count;
    }