Is there a simple way to use spring data couchbase with documents that do not have _class
attribute?
In the couchbase I have something like this in my sampledata
bucket:
{
"username" : "alice",
"created" : 1473292800000,
"data" : { "a": 1, "b" : "2"},
"type" : "mydata"
}
Now, is there any way to define mapping from this structure of document to Java object (note that _class
attribute is missing and cannot be added) and vice versa so that I get all (or most) automagical features from spring couchbase data?
Something like:
If type
field has value "mydata" use class MyData.java.
So when find is performed instead of automatically adding AND _class = "mydata"
to generated query add AND type = "mydata"
.
Spring Data in general needs the
_class
field to know what to instantiate back when deserializing.It's fairly easy in Spring Data Couchbase to use a different field name than
_class
, by overriding thetypeKey()
method in theAbsctractCouchbaseDataConfiguration
.But it'll still expect a fully qualified classname in there by default
Getting around that will require quite a bit more work:
CouchbaseTypeMapper
, following the model ofDefaultCouchbaseTypeMapper
. In thesuper(...)
constructor, you'll need to provide an additional argument: a list ofTypeInformationMapper
. The default implementation doesn't explicitly provide one, so aSimpleTypeInformationMapper
is used, which is the one that puts FQNs.Map
:ConfigurableTypeInformationMapper
... 3.So by putting aConfigurableTypeInformationMapper
with the alias you want for specific classes + aSimpleTypeInformationMapper
after it in the list (for the case were you serialize a class that you didn't provide an alias for), you can achieve your goal.typeMapper
is used within theMappingCouchbaseConverter
, which you'll also need to extend unfortunately (just to instantiate yourtypeMapper
instead of the default.MappingCouchbaseConverter
that uses your customCouchbaseTypeMapper
(themappingCouchbaseConverter()
method).In your couchbase configuration class you just need to have :
Unfortunately for query derivation (n1ql) the _class or type are still using the class name.Tried spring couch 2.2.6 and it's minus point here. @Simon, are you aware that something has changed and the support to have the possibility to have custom _class/type value in next release(s)?