How to use spring data with couchbase without _cla

2019-02-15 23:34发布

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

2条回答
Anthone
2楼-- · 2019-02-16 00:19

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.
  3. The typeMapper is used within the MappingCouchbaseConverter, which you'll also need to extend unfortunately (just to instantiate your typeMapper instead of the default.
  4. Once you have that, again override the configuration to return an instance of your custom MappingCouchbaseConverter that uses your custom CouchbaseTypeMapper (the mappingCouchbaseConverter() method).
查看更多
在下西门庆
3楼-- · 2019-02-16 00:23

In your couchbase configuration class you just need to have :

@Override
public String typeKey() {
    return "type";
}

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)?

查看更多
登录 后发表回答