当value为null时,将HashMap值存储到数据库中

时间:2015-10-12 09:33:52

标签: java mysql exception null spring-data

我必须通过Spring数据将我的HashMap<String,Object>存储到数据库MySql中。 要从HashMap检索数据,我使用键值,可能会发生键不存在,在这种情况下,我必须避免使用set方法存储到数据库中,因为我将值转换为String或int或float,在本例中为java抛出null异常。 鉴于我有很多行要存储到数据库中,我不想在所有代码行上使用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);

1 个答案:

答案 0 :(得分:0)

不确定这是不是您的意思,但我的想法是在您的班级中添加以下帮助方法:

 @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);

这样,如果地图中的值为dpfWeighting::setUnladenWeight

,则不会调用null个消费者