Thursday, November 18, 2010

Java / Ektorp / CouchDB

Ektorp is a persistence API that uses CouchDB as storage engine. The goal of Ektorp is to combine JPA like functionality with the simplicity and flexibility that CouchDB provides ... more ...

Below is an example that I used to access my CouchDB and I ran the command curl --user user:password -X PUT http://my.couchone.com:5984/testdb/ektorp -d '{ "color": "red" }' first to create a document 'ektorp' before executing Java code.


import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;
import org.ektorp.support.CouchDbDocument;

public class Ektorp {
public static void main(String[] args) {
HttpClient httpClient = new StdHttpClient.Builder()
.host("my.couchone.com")
.port(5984)
.username("user")
.password("password")
.build();

CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
CouchDbConnector db = new StdCouchDbConnector("testdb", dbInstance);

db.createDatabaseIfNotExists();
Sofa sofa = db.get(Sofa.class, "ektorp");

if (sofa.getColor().equals("red")) {
sofa.setColor("green");
} else {
sofa.setColor("red");
}
db.update(sofa);
}
}

class Sofa extends CouchDbDocument {
private String color;
public void setColor(String s) {
color = s;
}

public String getColor() {
return color;
}
}

More examples here ...

No comments: