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:
- Public ClassTweetImplementsDBObject {
- /*...*/
- }
- Tweet myTweet =NewTweet ();
- MyTweet. put ("User", UserId );
- MyTweet. put ("Message", Msg );
- MyTweet. put ("Date",NewDate ());
- Collection. insert (myTweet );
- Collection. setObjectClass (Tweet.Class);
- Tweet myTweet = (Tweet) collection. findOne ();
- Tweet myTweet = (Tweet) collection. findOne ();
- MyTweet. put ("Message", NewMsg );
- Collection. save (myTweet );
You may have discovered that this method only applies to new classes. It is not suitable for the original classes.