Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use spring data with couchbase without _class attribute

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

like image 318
Milan Avatar asked Aug 09 '16 09:08

Milan


1 Answers

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:

  1. You'll need to implement your own 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.
  2. There's an alternative implementation that is configurable so you can alias specific classes to a shorter name via a Map: ConfigurableTypeInformationMapper...
  3. So by putting a 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.
  4. The typeMapper is used within the MappingCouchbaseConverter, which you'll also need to extend unfortunately (just to instantiate your typeMapper instead of the default.
  5. Once you have that, again override the configuration to return an instance of your custom MappingCouchbaseConverter that uses your custom CouchbaseTypeMapper (the mappingCouchbaseConverter() method).
like image 199
Simon Baslé Avatar answered Sep 19 '22 13:09

Simon Baslé