Getting spring-data-mongo to insert null values into the db

Viewed 354

I need to serialize all null valued fields to the mongodb using spring-data-mongo repositories. Unfortunately, I couldn't find any configuration option, and I don't want to make all the nullable fields Optional and writing custom converter for them, so the question is, is there any other option than extending MappingMongoConverter like that ?

/**
 * The converter that, as opposed to the default one, serializes null properties
 * Unfortunately DocumentAccessor class is package private so the class must reside in spring package
 */
public class NullSerializingMappingMongoConverter extends MappingMongoConverter {

    public NullSerializingMappingMongoConverter(DbRefResolver dbRefResolver,
                                                MappingContext<? extends MongoPersistentEntity<?>,
                                                        MongoPersistentProperty> mappingContext) {
        super(dbRefResolver, mappingContext);
    }

    @Override
    protected void writeInternal(Object obj, Bson bson, MongoPersistentEntity<?> entity) {
        if(obj == null)
            return;
        super.writeInternal(obj, bson, entity);

        PersistentPropertyAccessor<?> accessor = entity.getPropertyAccessor(obj);

        for (MongoPersistentProperty prop : entity) {
            Object value = accessor.getProperty(prop);
            if(value == null){
                DocumentAccessor documentAccessor = new DocumentAccessor(bson);
                documentAccessor.put(prop, null);
            }

        }
    }
}
0 Answers
Related