2

http://www.mongodb.org/display/DOCS/Java+-+Saving+Objects+Using+DBObject

This page is about saving and retrieving objects in MongoDB. But after implementing DBObject, I have to override a bunch of methods. Does anyone know how to implement a PUT method so that "myTweet.put("user", userId);" can work?

4

1 回答 1

4

Instead of implementing DBObject just extend BasicDBObject

class Tweet extends BasicDBObject {
  public Tweet() {
    super();
  }
  public Tweet(BasicDBObject base) {
    super();
    this.putAll(base);
  }
}

Tweet myTweet = new Tweet();
myTweet.put("user", userId);

BasicDBObject implements DBObject so a class that extends it can be passed to any function that expects a class that implements DBObject. If you wanted to implement the interface you would have to supply some container class to store the tweet attributes BasicDBObject does this by extending another class called BasicBSONObject which you can see in the source, a naive implementation would look like this:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.bson.BSONObject;

import com.mongodb.DBObject;


public class Tweet implements DBObject {
    private Map<String, Object> data;
    private boolean partial;

    public Tweet() {
        data = new HashMap<>();
        partial = false;
    }

    @Override
    public Object put(String key, Object value) {
        return data.put(key, value);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void putAll(BSONObject o) {
        data.putAll(o.toMap());
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void putAll(Map m) {
        data.putAll(m);
    }

    @Override
    public Object get(String key) {
        return data.get(key);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Map toMap() {
        return data;
    }

    @Override
    public Object removeField(String key) {
        return data.remove(key);
    }

    @Override
    public boolean containsKey(String key) {
        return data.containsKey(key);
    }

    @Override
    public boolean containsField(String key) {
        return data.containsKey(key);
    }

    @Override
    public Set<String> keySet() {
        return data.keySet();
    }

    @Override
    public void markAsPartialObject() {
        partial = true;
    }

    @Override
    public boolean isPartialObject() {
        return partial;
    }
}

This class implements the DBObject and uses a HashMap to store it's properties.

于 2012-11-27T05:48:48.407 回答