MongoDB-Escape dots '.' in map key]
My exception:
org.springframework.data.mapping.MappingException: Map key VAT Registration No. contains dots but no replacement was configured! Make sure map keys don't contain dots in the first place or configure an appropriate replacement!
Field with a dot at the end: VAT Registration No.
This didn't work for me:
mongoConverter.setMapKeyDotReplacement(".");
mongoConverter.setMapKeyDotReplacement("_"); //this broke enum values for example VALUE_1 -> VALUE.1
This works for me:
mongoConverter.setMapKeyDotReplacement("-DOT")
Complete class:
@Configuration
public class MongoConfiguration {
@Bean
public MappingMongoConverter mongoConverter(MongoDbFactory mongoFactory, MongoMappingContext mongoMappingContext) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
mongoConverter.setMapKeyDotReplacement("-DOT");
return mongoConverter;
}
}
When using Spring Data MongoDB you get an instance of: org.springframework.data.mongodb.core.convert.MappingMongoConverter
that has mapKeyDotReplacement
set to null by default - that is why you are getting an exception.
You need to either create your own instance of org.springframework.data.mongodb.core.convert.MappingMongoConverter
or just modify existing instance using its provider setter method:
/**
* Configure the characters dots potentially contained in a {@link Map} shall be replaced with. By default we don't do
* any translation but rather reject a {@link Map} with keys containing dots causing the conversion for the entire
* object to fail. If further customization of the translation is needed, have a look at
* {@link #potentiallyEscapeMapKey(String)} as well as {@link #potentiallyUnescapeMapKey(String)}.
*
* @param mapKeyDotReplacement the mapKeyDotReplacement to set
*/
public void setMapKeyDotReplacement(String mapKeyDotReplacement) {
this.mapKeyDotReplacement = mapKeyDotReplacement;
}
In MongoDB, dot is always treated as a special character so avoiding it will most likely save you some other headache in the future.
EDIT:
To override default MappingMongoConverter
add the following bean declaration:
@Bean
public MappingMongoConverter mongoConverter(MongoDbFactory mongoFactory) throws Exception {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
mongoConverter.setMapKeyDotReplacement(".");
return mongoConverter;
}