couchdbektorp

ektorp / CouchDB mix HashMap and Annotations


In jcouchdb I used to extend BaseDocument and then, in a transparent manner, mix Annotations and not declared fields. Example:

import org.jcouchdb.document.BaseDocument;

public class SiteDocument extends BaseDocument {
    private String site;

    @org.svenson.JSONProperty(value = "site", ignoreIfNull = true)
    public String getSite() {
        return site;
    }

    public void setSite(String name) {
        site = name;
    }
}

and then use it:

// Create a SiteDocument
SiteDocument site2 = new SiteDocument();
site2.setProperty("site", "http://www.starckoverflow.com/index.html");
// Set value using setSite
site2.setSite("www.stackoverflow.com");
// and using setProperty
site2.setProperty("description", "Questions & Answers");
db.createOrUpdateDocument(site2);

Where I use both a document field (site) that is defined via annotation and a property field (description) not defined, both get serialized when I save document.

This is convenient for me since I can work with semi-structured documents.

When I try to do the same with Ektorp I have documents using annotations and Documents using HashMap BUT I couldn't find an easy way of getting the mix of both (I've tried using my own serializers but this seems to much work for something that I get for free in jcouchdb). Also tried to annotate a HashMap field but then is serialized as an object and I get the fields automatically saved BUT inside an object with the name of the HashMap field.

Is it possible to do (easily/for free) using Ektorp?


Solution

  • It is definitely possible. You have two options:

    1. Base your class on org.ektorp.support.OpenCouchDbDocument
    2. Annotate the you class with @JsonAnySetter and @JsonAnyGetter. Red more here: http://wiki.fasterxml.com/JacksonFeatureAnyGetter