Insert Document


Now that you have a connection to an existing Database (see Create a Database) you might start inserting documents into it.

We will use a jcouchdb BaseDocument (implementation of Document interface) that provides methods for setting and getting properties from the document in addition to setting and getting Id and Revision.

// Create a first document
BaseDocument doc1 = new BaseDocument();
doc1.setProperty("name", "onabai");

// Persist document
db.createDocument(doc1);

// Display Id and Revision for stored document
System.out.printf("Id: %s Revision: %sn", doc1.getId(), doc1.getRevision());

Important to note that CouchDB is a MVCC Database  meaning that for one document it stores multiple versions of it (each time you update a document it saves a new version, instead of overwriting previous copy). Said so, CouchDB will uniquely identify a document using itsidentifier and its revision. Revision is updated each time a document is saved while the identifier persists.

The output showing identifier and revision, might be something like:

Id: a2011483f0a0dce0eed2df14e6007cfb Revision: 1-fff06fa1e6224105f49dbecd6d8b7398

In previous example, we created a BaseDocument (new BaseDocument())and then set a property called name and a value of onabai (doc1.setProperty(“name”, “onabai”)). Then we create (persist) the document in CouchDB using Database method createDocument(doc1).

As result of persisting it, the document gets updated and assigned the identifier and revision.

In this example we let CouchDB to automatically assign the identifier but you might choose to assign it manually as in the following example:

// Create a document and use our own id 
BaseDocument myDoc = new BaseDocument(); 
myDoc.setId("my.own.id-" + System.currentTimeMillis()); 
myDoc.setProperty("name", "onabai"); 

// Persist document 
db.createDocument(myDoc); 

// Display Id and Revision for stored document 
System.out.printf("Id: %s Revision: %sn", myDoc.getId(), myDoc.getRevision());

and get the following output:

Id: my.own.id-1336128565532 Revision: 1-fff06fa1e6224105f49dbecd6d8b7398

Creating you own identifiers gives you freedom and maybe it might even be convenient when you have to access the document but you need to make sure to do not reuse it or you will get a conflict exception.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s