Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Data Couchbase: Handle Unknown Class

DZone 's Guide to

Spring Data Couchbase: Handle Unknown Class

· Java Zone ·
Free Resource

Spring Data Couchbase  provides transparent way to save and load Java classes to and from Couchbase.

However, if a loaded class contains a property of unknown class, you will receive org.springframework.data.mapping.model.MappingException: No mapping metadata found for java.lang.Object

This may happen if, for example, different versions of your code save and load information.

In order to handle situation when we want to load an object, which contains another object on unknown class (in a map or list property) we should override the default SPMappingCouchbaseConverter.

Let's see how we do this with Spring XML configuration:

I replace my old XML:


<couchbase:couchbase id="cache" host="${couchbase.host}" bucket="mycache" password="password"/>
<couchbase:template id="cache-template" client-ref="cache"/>
<couchbase:repositories base-package="com.mycompany.cache" couchbase-template-ref="cache-template"/>


to the following XML:

<bean id="mappingContext"
          class="org.springframework.data.couchbase.core.mapping.CouchbaseMappingContext"/>
<bean id="converter"
          class="com.mycompany.MyMappingCouchbaseConverter">
        <constructor-arg name="mappingContext" ref="mappingContext"/>
</bean>

<couchbase:couchbase id="cache" host="${couchbase.host}" bucket="mycache" password="password"/>
<bean id="cache-template" class="org.springframework.data.couchbase.core.CouchbaseTemplate">
        <constructor-arg name="client" ref="cache"/>
        <constructor-arg name="couchbaseConverter" ref="converter"/>
        <constructor-arg name="translationService">
            <null/>
        </constructor-arg>
 </bean>


<couchbase:repositories base-package="com.mycompany.cache" couchbase-template-ref="cache-template"/>


And create the following class:


public class MyMappingCouchbaseConverter extends MappingCouchbaseConverter {

    public MyMappingCouchbaseConverter(final MappingContext<? extends CouchbasePersistentEntity<?>,            CouchbasePersistentProperty> mappingContext) {
        super(mappingContext);
    }

    @Override
    protected <R> R read(final TypeInformation<R> type, final CouchbaseDocument source, final Object parent) {
        if (Object.class == typeMapper.readType(source, type).type) {
            return null;
        }

        return super.read(type, source, parent);
    }
}

Now, if loaded object will contain a property of unknown class or an object of unknown class in a list or map, this property or object will be replaced by null.



Topics:
xml ,spring ,couchbase

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}