java - 当值为 null 时将 HashMap 值存储到数据库中

标签 java mysql exception null spring-data

我必须存储我的 HashMap<String,Object>通过Spring data导入数据库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);

最佳答案

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

 @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 消费者

关于java - 当值为 null 时将 HashMap 值存储到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33077759/

相关文章:

java - Hibernate更新突然不起作用

mysql - 编写此日期范围范围的更好方法是什么?

c# - 删除 BoxCollider 时的 Unity3D MissingReferenceException

java - java中web服务不可用时如何处理异常

java - Apache POI "smart drag copy"单元格

Java暂停程序执行

mySQL 多重 INNER JOIN

php - CMS 内部搜索引擎中的 PageRank

C# SmtpClient.Send() - 处理异常的任何替代方法(或伴侣)?

java - Spring 网络应用程序