I have an existing mongo database in which ids (_id) are persisted as plain Strings.. This is sample data in Mongo DB:
{
\"_id\" : \"528bb0e2e4b0442f1479
There's a converter behind which does this conversion out of the box for you, if you'd like to keep String id's as they're and not convert them to ObjectId you have to override the convertId method in the MappingMongoConverter
class, I've made an example here:
/*
* Note that this example I've tried on spring-data-mongodb.3.0.4.RELEASE version
* and it's not guaranteed that it will work with earlier versions
* yet the approach should be similar
*/
@Component
public class CustomMappingMongoConverter extends MappingMongoConverter {
public CustomMappingMongoConverter(MappingContext extends MongoPersistentEntity>, MongoPersistentProperty> mappingContext) {
//The constructor can differ based on the version and the dbRefResolver instance as well
super(NoOpDbRefResolver.INSTANCE, mappingContext);
}
@Override
public Object convertId(Object id, Class> targetType) {
if (id == null) {
return null;
} else if (ClassUtils.isAssignable(ObjectId.class, targetType) && id instanceof String && ObjectId.isValid(id.toString())) {
return id;
}
return super.convertId(id, targetType);
}
}