【问题标题】:Store HashMap values into database when value is null当值为空时将 HashMap 值存储到数据库中
【发布时间】:2016-01-09 17:36:19
【问题描述】:

我必须通过 Spring 数据将我的 HashMap<String,Object> 存储到数据库 MySql 中。 要从 HashMap 检索数据,我使用键值,并且可能会发生键不存在的情况,在这种情况下,我必须避免使用 set 方法存储到数据库中,因为我将值转换为 String 或 int 或 float,在这种情况下为 java抛出空异常。 鉴于我有很多行要存储到数据库中,我不想在所有代码行上都使用 If 子句,但我该怎么做呢?

@Override
public void archiveAcquisition(HashMap<String,Object> rowValues, int index) {
        switch(index){
        case 1:
            firstRowValues=rowValues;
            break;
        case 2:
            secondRowValues=rowValues;
            break;
        case 3:
            thirdRowValues=rowValues;
            break;
        default:
            actualRowValues=rowValues;

            AvoidNullValueError(ExcelMappingCoordinate.shift,index);

            Shift shift=new Shift(actualRowValues.get(ExcelMappingCoordinate.shift.getCoordinate()+index).toString());
            shiftServices.create(shift);
            MissionProfile missionProfile=new MissionProfile(actualRowValues.get(ExcelMappingCoordinate.missionProfile.getCoordinate()+index).toString());
            missionProfileServices.create(missionProfile);
            DpfWeighting dpfWeighting=new DpfWeighting();
            dpfWeighting.setUnladenWeight((float)actualRowValues.get(ExcelMappingCoordinate.unladenWeight.getCoordinate()+index));
            dpfWeighting.setGrossWeight((float)actualRowValues.get(ExcelMappingCoordinate.grossWieght.getCoordinate()+index));
            dpfWeighting.setDpfTemperature((float)actualRowValues.get(ExcelMappingCoordinate.dpfTemperature.getCoordinate()+index));
            dpfWeightingServices.create(dpfWeighting);
            OilSample oilSample=new OilSample();
....
....

例如我做了

if ((value=actualRowValues.get(ExcelMappingCoordinate.unladenWeight.getCoordinate()+index))!=null)
                dpfWeighting.setUnladenWeight((float)value);

【问题讨论】:

    标签: java mysql exception null spring-data


    【解决方案1】:

    不确定这是否是您的意思,但我的想法是在您的类中添加以下辅助方法:

     @SuppressWarnings("unchecked")
     <V> void ifPresent(Map<String, Object> map, String key, Consumer<V> consumer) {
        V value = (V) map.get(key);
        if (value != null) {
            consumer.accept(value);
        }
    }
    

    那就不用写了

    dpfWeighting.setUnladenWeight((float)actualRowValues.get(
    ExcelMappingCoordinate.unladenWeight.getCoordinate()+index));
    

    您可以像这样使用ifPresent 方法:

    ifPresent(actualRowValues,
    ExcelMappingCoordinate.unladenWeight.getCoordinate()+index,
    dpfWeighting::setUnladenWeight);
    

    如果地图中的值为null,则不会调用dpfWeighting::setUnladenWeight消费者

    【讨论】:

    • 是的,我想用一种方法实现上面的 if 子句。我认为您的方法是正确的,但是如果 'if (value != null)' 我必须转换为 String、int 或 float 取决于 setMethod
    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    相关资源
    最近更新 更多