发布于 2015-09-14 15:10:01 | 113 次阅读 | 评论: 0 | 来源: 网络整理

The Java driver provides a DBObject interface to save custom objects to the database.

For example, suppose one had a class called Tweet that they wanted to save:

public class Tweet implements DBObject {
    /* ... */
}

Then you can say:

Tweet myTweet = new Tweet();
myTweet.put("user", userId);
myTweet.put("message", msg);
myTweet.put("date", new Date());

collection.insert(myTweet);

When a document is retrieved from the database, it is automatically converted to a DBObject. To convert it to an instance of your class, use DBCollection.setObjectClass():

collection.setObjectClass(Tweet.class);

Tweet myTweet = (Tweet)collection.findOne();

If for some reason you wanted to change the message you can simply take that tweet and save it back after updating the field.

Tweet myTweet = (Tweet)collection.findOne();
myTweet.put("message", newMsg);

collection.save(myTweet);
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务