'Handle collection of mixed doubles and nulls in Spring Data MongoDB
I have a Mongo document that, among other things, has an object that stores a list of doubles:
id: ...,
metrics : [
{
name: "miles/hr",
values : [
10.0,
10.4,
10.2,
11.0
]
}
]
I'm using Spring data to read these objects from the collection using the following Java object:
public class Performance {
public String id;
public List<Metric> metrics = new ArrayList();
}
public class Metric {
public String name;
public List<Double> values;
}
And the repository is pretty basic:
@Repository
public interface PerformanceRepository extends MongoRepository<Performance, String> {
List<Performance> findByIdIn(Collection<String> ids);
}
My problem is that this data comes from an external data provider, and on some occasions I get a mix of doubles and nulls:
id: xxx,
metrics : [
{
name: "miles/hr",
values : [
10.0,
null,
null,
11.0
]
}
]
This causes null pointer exceptions in the Spring repository:
java.lang.NullPointerException: null
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$ConversionContext.convert(MappingMongoConverter.java:1885) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readCollectionOrArray(MappingMongoConverter.java:1139) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$$Lambda$1773/000000000000000000.convert(Unknown Source) ~[na:na]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$ConversionContext.convert(MappingMongoConverter.java:1900) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1636) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:477) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.populateProperties(MappingMongoConverter.java:392) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:371) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readDocument(MappingMongoConverter.java:341) ~[spring-data-mongodb-3.2.2.jar:3.2.2]
Is there a way to gracefully handle these documents, perhaps through an annotation on the metrics field or a custom query? Ideally I just want to convert the null entries to a default value like 0.0 rather than just discard them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
