java遇到的问题整理

开发框架 :springboot+mybatis +达梦数据库

开发工具:idea

目录

Mapper层

新增

条件查询

in list ([1,2,3,4])

in string ("1,2,3,4")

in string ("type1,type2,type2")

>=和“<=”

日期处理

Service层 

事务

数据类型转换

1.list转map

2.list转list

3.string转map

4.map转list

数据筛选

请求

获取header参数

获取上传文件

日期处理

其他问题


Mapper层

  • 新增

<insert id="Insert" parameterType="com.sh3h.lams.core.entity.WsmpIndicator" useGeneratedKeys="true" keyColumn="INDICATOR_ID" keyProperty="indicatorId">
    INSERT INTO WSMP_INDICATOR
    (OBJECT_ID,INDICATOR_NAME,INDICATOR_CODE,INDICATOR_ALIAS,INDICATOR_TYPE,INDICATOR_DATA_TYPE,INDICATOR_STATE,INDICATOR_PROP,SCADA_OBJECT_ID)
    VALUES
    (#{objectId,jdbcType=INTEGER},
     #{indicatorName,jdbcType=VARCHAR},
     #{indicatorCode,jdbcType=VARCHAR},
     #{indicatorAlias,jdbcType=VARCHAR},
     #{indicatorType,jdbcType=VARCHAR},
     #{indicatorDataType,jdbcType=VARCHAR},
     #{indicatorState,jdbcType=INTEGER},
     #{indicatorProp,jdbcType=VARCHAR},
     #{scadaObjectId,jdbcType=INTEGER})
</insert>
  • 条件查询

  1. in list ([1,2,3,4])

    <where> 1=1
        <if test="condition.ObjectIdList!=null and condition.ObjectIdList!=''">
            and OBJECT_ID in
            <foreach collection="condition.ObjectIdList" open="(" close=")" separator="," item="objectId">
                #{objectId}
            </foreach>
        </if>
    </where>

  2. in string ("1,2,3,4")

    and  UM.AREA_ID  in (${condition.areaIds})
  3. in string ("type1,type2,type2")

    where DTY_TYPE in
    <foreach collection="dtyTypes.split(',')" index="index" item="type" open="(" separator="," close=")">
        #{type,jdbcType=VARCHAR}
    </foreach>

  4. >=和“<=”

    DATA_DATE<![CDATA[ >= ]]>#{startDate} and DATA_DATE<![CDATA[ <= ]]>#{endDate}

  5. 日期处理

      --https://blog.csdn.net/whenyoucome/article/details/84183472
      select sysdate,to_char(sysdate+1,'yyyy-mm-dd HH24:MI:SS') from dual; --当前日期加1天
      select to_date(sysdate-1,'yyyy-mm-dd HH24:MI:SS') from dual;--当前日期减1天,日期类型(支持日期比较)
      select sysdate,to_char(to_date('2022-02-25 14:53:41')+1,'yyyy-mm-dd HH24:MI:SS') from dual;--指定日期加1天

Service层 

  • 事务

DefaultTransactionDefinition def=new DefaultTransactionDefinition();
def.setName("saveall-tran");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

TransactionStatus status=transactionManager.getTransaction(def);
try {
    boolean result=true;
    if(result) {
        wsmpVersionService.updateByCode(WsmpConsts.VERSION_CODE);
        removeDataCache();
        transactionManager.commit(status);
    }
    else
        transactionManager.rollback(status);
    return result;
}
catch (Exception e){
    transactionManager.rollback(status);
    System.out.println(e);
    return false;
}

  • 数据类型转换

1.list转map

Map<Integer, WsmpLayerDto> dicLayer=layerService.selectAll().stream().collect(Collectors.toMap(WsmpLayerDto::getLayerId, Function.identity()));

2.list转list

List<Object> list=redisTemplate.opsForHash().values(WsmpConsts.URN_PREFIX_WSMP_OBJECT);
List<WsmpObjectDto> objects=list.stream().map(p -> JSONUtil.toBean(JSONUtil.toJsonStr(p), WsmpObjectDto.class)).collect(Collectors.toList());

3.string转map

HashMap<String, LamsIndicatorPropertyData> dicIndicatorProperty = new HashMap<String, LamsIndicatorPropertyData>();
LamsSettings settingIndicatorProperty = settingsService.selectSettingByCode("INDICATOR_PROPERTY");
if (settingIndicatorProperty != null && !(settingIndicatorProperty.getValue()!=null))
{
        Gson gson = new Gson();
        String jsonString=settingIndicatorProperty.getValue();
        dicIndicatorProperty =gson.fromJson(jsonString, dicIndicatorProperty.getClass());
}

4.map转list

diclist.values().stream().collect(Collectors.toList());
  • 数据筛选

list找第一条数据

List<LamsScadaLiveData> ScadaLiveList = null; ScadaLiveList.stream().filter(t -> t.indicatorId == item.getIndicatorId()).findAny().orElse(null);

过滤-单一条件

//int用==
objExtends.stream().filter(e->e.getId()==id).collect(Collectors.toList()); 
//string用equals 
allZone.stream().filter(z->z.objectName.equals(entity.AreaName)).findFirst().orElse(null);

过滤-多条件

WsmpDictionary dic=allDictionary.stream().filter(t->t.dtyType=="METER_TYPE" && t.dtyName == entity.MeterTypeName).findFirst().orElse(null);

map循环


public HashMap<WsmpIndicator, List<WsmpIndExtendDto>> DicIndicator ;
DicIndicator.forEach((key, value) -> {
    WsmpIndicator indicator = new WsmpIndicator();
    indicator.indicatorId = key.getIndicatorId();
    indicator.objectId = key.getObjectId();
    indicator.indicatorName = key.getIndicatorName();
    indicator.indicatorCode = key.getIndicatorCode();
    if (value.size() > 0) {
        for (WsmpIndExtendDto indicatorExend : value) {
            indicatorExend.setId(indicator.indicatorId);
            indicatorExtendService.addIndicatorExtend(indicatorExend);
        }
    }
});

list循环

//方法一
List<WsmpObjectOutput> result = objectList.stream().map(u -> {
    WsmpObjectOutput newobject = new WsmpObjectOutput(u);
    int id = newobject.getObjectId();

    List<WsmpIndicatorOutput> indicators = allIndicators.stream().filter(i->i.getObjectId()==id).collect(Collectors.toList());
    newobject.setIndicators(indicators);

    WsmpLayerDto layer = dicLayer.get(newobject.getLayerId());
    newobject.setLayer(layer);

    return newobject;
}).collect(Collectors.toList());


//方法二
for (LamsUserMeterMap model : entityList) {
 }

json类型转换

  1. string转object 并获取某个属性值
JSONObject prop=output.getIndicatorProperty();
if(prop!=null && prop.get("unit") != null){
    String str=prop.get("unit").toString();
    if(StringUtil.isNotEmpty(str) && str!=""){
        int unitId= Integer.parseInt(str);
        WsmpUnit unit=dicUnit.get(unitId);
        output.setUnit(unit);
    }
}

请求

  • 获取header参数

int userId =0;
HttpServletRequest request1=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if(request1!=null)
    userId =Integer.parseInt(request1.getHeader("userId"));
  • 获取上传文件

@WapHttpAction("excelToDoUserMeterValid")
@ResponseBody//返回json数据
@PostMapping("excelToDoUserMeterValid")
public WapResponse<ExcelReturn> ExcelToDoUserMeterValid(HttpServletRequest request,
                                                        HttpServletResponse response, int userId, String indicatorTypes) throws IOException
{
    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
        Iterator iter = mr.getFileMap().values().iterator();

        if (iter.hasNext()) {
            MultipartFile file = (MultipartFile) iter.next();
            ExcelReturn result = Service.ExcelToDoUserMeterValid(file,userId, indicatorTypes);
            return new WapResponse<ExcelReturn>(result);
        }
        else
            return null;
    }
    else
        return null;
}


日期处理

//model
@TableField("UPDATE_TIME")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date UpdateTime ;
//mapper
UPDATE_TIME =  SYSDATE()
//service
//将时间字符串形式转化为日期对象
DateTimeFormatter dtf0 = DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00");
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59");

String strStartTime =LocalDateTime.now().plus(-1, ChronoUnit.DAYS).format(dtf0);
String strEndTime = LocalDateTime.now().plus(-1, ChronoUnit.DAYS).format(dtf1);;
LocalDateTime startTime=LocalDateTime.parse(strStartTime,dtf0);
LocalDateTime endTime =LocalDateTime.parse(strEndTime,dtf1);

其他问题

  • json转换忽略null值,避免报错
//https://www.cnblogs.com/liaojie970/p/9396334.html
//application.properties
spring.jackson.defaultPropertyInclusion=NON_EMPTY
  • 达梦数据库:表名和列名如果有小写的,必须加“”才能查,不然就是无效的


版权声明:本文为m0_57478867原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。