using-couchdb-with-java-and-domain

This is a simple application using CouchDB in a Java program. I'm using the LightCouch JAR downloaded from  www.lightcouch.org; the current version was 0.0.4 when I downloaded it. This version of my code uses a domain class; if there is enough demand (e-mail me at euric.reiks@gmail.com), I'll post the JSON version too.

First, I generated a Java package called "org.lightcouchtest4.oop" in my LightCouchTest4 project. The next step was creating a "properties" file in the root of my package called "couchdb2.properties". "couchdb.properties" is the default for this purpose, but I already had one. Here is what it looks like...


# To change this template, choose Tools | Templates
# and open the template in the editor.
couchdb.name=db-java4-oop
couchdb.createdb.if-not-exist=true
couchdb.protocol=http
couchdb.host=127.0.0.1
couchdb.port=5984
couchdb.username=
couchdb.password=

I hope these settings are self-explanatory. You might need to use different values in your file. Yes, LightCouch will create the database if it doesn't exist when you set "couchdb.createdb.if-not-exist" to true.

The next step is to construct the directory tree for the database views. These are sort of like stored procedures. In CouchDB, queries are created in design document JSON objects, with JavaScript doing the heavy lifting. With LightCouch, you just need the JavaScript. At the root of my package, I created two directory paths, /design-docs/example/views/by_all and /design-docs/example/views/by_name. In the first path, I created a map.js file containing


function(doc) {
emit(doc, doc);
}

This might look silly, but it enables me to retrieve all my documents of a given type at once. In version 0.0.4, this might be the only way to do it. The other path ends in a map.js file containing


function(doc) {
emit([doc.first, doc.last], doc);
}

This slight-of-hand enables me to search on a first name and a last name simultaneously. This program stores people's names, but first checks to make sure the name isn't already on file. What does the Name class look like? I'm glad you asked...


package org.lightcouchtest4.oop;
import org.lightcouch.*;
/**
 *
 * @author Ross
 */
public class Name extends Document {
    public String first;
    public String middle;
    public String last;
}

The Document class gives my Name objects an _id and a _rev. Adding a Name object to the database generates these attributes automatically. If you use Map<String, Object> to create your documents, you'll have to generate the _id's yourself.

Now for the main code.  Here is the whole enchilada:


package org.lightcouchtest4.oop;
import java.util.*;
import org.lightcouch.*;

/**
 *
 * @author Ross
 */
public class Main {
    public static void main(String[] args) {
        CouchDbClient dbClient = new CouchDbClient("couchdb2.properties");
        DesignDocument designDoc;
        designDoc = dbClient.design().getFromDesk("example");
        Response response;
        response = dbClient.design().synchronizeWithDb(designDoc);
        
        Scanner sc = new Scanner(System.in);
        System.out.print("First name: ");
        String firstName = sc.nextLine();
        System.out.print("Middle name: ");
        String middleName = sc.nextLine();
        System.out.print("Last name: ");
        String lastName = sc.nextLine();
        
        int dupCount;
        String[] keys = {firstName, lastName};
        dupCount = dbClient.view("example/by_name").key((Object[]) keys)
                .query(Name.class).size();
        
        if (dupCount > 0) {
            System.out.println("Found a copy");
        }
        else {
            Name name = new Name();
            name.first = firstName;
            name.last = lastName;
            name.middle = middleName;
            dbClient.save(name);
            System.out.println("New name was submitted");
        }
        
        List<Name> names = dbClient.view("example/by_all")
                .includeDocs(true).query(Name.class);
        System.out.println("\n Names list:");
        for (Name myName : names) {
            System.out.println(myName.first + " " + 
                    myName.middle + " " +
                    myName.last);
        }
        dbClient.shutdown();
    }
    
    
}

Creating a CouchClient instance connects the program to CouchDB using the settings in the given file. The designDoc variable helps LightCouch locate the design document files on the hard drive; the response variable updates CouchDB with those design documents if necessary. dupCount gets the number of documents whose data matches the entered name. (The Object[] casting is necessary.) If matches are found, a message appears on the screen. Otherwise, the entered data gets stuffed into a Name object and submitted to CouchDB. You might be wondering why the last query doesn't have a key. That omission tells CouchDB to retrieve all the Name-typed documents. includeDocs(true) says to grab the entire documents; without that, you would have to first get the _id's of the documents, then execute find() with the _id values to get the actual data. Lastly, as you might have guessed, the shutdown() method prevents memory leaks and disconnects the database.

This code uses Java 7 syntax. You might have to make modifications if you're using an older version of Java.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值