1

When I try to persist @Document using CrudRepository, all null fields in the object does not get written to the database.

Example (Object obj):

{ 
    "field1": {
        "field11": 123
    },
    "field2": null,
    "field3": "abc"
}

objRepo.save(obj), field2 will not get written to Couchbase.

Is there a possibility to override the behavior of spring repository to save nulls? Do I have to create my own MappingCouchbaseConverter or maybe it have to do with the TranslationService?

prettyvoid
  • 3,446
  • 6
  • 36
  • 60

2 Answers2

2

There's no support for storing the nulls explicitly right now, so you might have to tinker with MappingCouchbaseConverter. I think modifying one of the writeInternal methods would be a good start: something like doing writeSimpleInternal(null, target, prop.getFieldName()); for the null case...

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
  • if you manage to make it sanely configurable, that would be a good candidate for a PR :) – Simon Baslé Sep 19 '16 at 10:20
  • Thank you for the information, I'll see what can I come up with. If you don't mind please check my other question: http://stackoverflow.com/questions/39571003/id-and-field-on-same-variable – prettyvoid Sep 19 '16 at 10:32
0

So I ran into the same issue and as of spring-data-couchbase 3.x, you need to extend the MappingCouchBaseConverter and basically overwrite a bunch of methods (mostly copying private methods).

The actual change is in

protected void writeInternal(final Object source, final CouchbaseDocument target,
        final CouchbasePersistentEntity<?> entity)

Where you will have to find the check for if (null != propertyObj) and add an else block with:

else {
    writeSimpleInternal(null, target, prop.getFieldName());
}

I feel like the spring team could probably just add an option to serialize null (or not) and then make this small change. But if you don't want to wait on those changes - just inherit from their class, overwrite and add the converter in your CouchBaseConfig as such:

@Override
public MappingCouchbaseConverter mappingCouchbaseConverter() throws Exception {
    CustomMappingCouchbaseConverter converter = new CustomMappingCouchbaseConverter(couchbaseMappingContext(), typeKey());
    converter.setCustomConversions(customConversions());
    return converter;
}
Schaka
  • 772
  • 9
  • 20