prettyvoid
prettyvoid

Reputation: 3706

Null values not persisted to Couchbase using spring-data-couchbase

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?

Upvotes: 1

Views: 1370

Answers (2)

Schaka
Schaka

Reputation: 772

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;
}

Upvotes: 0

Simon Basl&#233;
Simon Basl&#233;

Reputation: 28351

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...

Upvotes: 2

Related Questions