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 the typeKey()
method in the AbsctractCouchbaseDataConfiguration
.
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 of DefaultCouchbaseTypeMapper
. In the super(...)
constructor, you'll need to provide an additional argument: a list of TypeInformationMapper
. The default implementation doesn't explicitly provide one, so a SimpleTypeInformationMapper
is used, which is the one that puts FQNs.Map
: ConfigurableTypeInformationMapper
...ConfigurableTypeInformationMapper
with the alias you want for specific classes + a SimpleTypeInformationMapper
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 the MappingCouchbaseConverter
, which you'll also need to extend unfortunately (just to instantiate your typeMapper
instead of the default.MappingCouchbaseConverter
that uses your custom CouchbaseTypeMapper
(the mappingCouchbaseConverter()
method).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With