Three methods for MongoDB to save Java objects

Source: Internet
Author: User

MongoDB has three methods to save java objects. One is to implement the DBObject interface through a class, and the other is to use the object ing function of the spring-mongodb tool, converts a java object to the BSON document of MongoDB. One is to convert the object to binary storage through a serialization instance. MongoDB supports binary data format. The following describes three methods:

1. Implement the DBObject Interface

If this method is used, the class is still a DBObject. The put and get methods are used to access object attributes, which is inconvenient. For details, refer to the example on the official website:

  1. Public ClassTweetImplementsDBObject {
  2. /*...*/
  3. }
  1. Tweet myTweet =NewTweet ();
  2. MyTweet. put ("User", UserId );
  3. MyTweet. put ("Message", Msg );
  4. MyTweet. put ("Date",NewDate ());
  5. Collection. insert (myTweet );
  1. Collection. setObjectClass (Tweet.Class);
  2. Tweet myTweet = (Tweet) collection. findOne ();
  1. Tweet myTweet = (Tweet) collection. findOne ();
  2. MyTweet. put ("Message", NewMsg );
  3. Collection. save (myTweet );

You may have discovered that this method only applies to new classes. It is not suitable for the original classes.

  • 1
  • 2
  • Next Page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.