Java Operation MongoDB Save/Read Java object to/from MongoDB

Source: Internet
Author: User
Tags mongoclient mongodb save tojson

MongoDB official Java driver, save and read, the need is DBObject object, this is an interface, implement Put,get and other methods, similar to map, if we want to directly save ordinary Java objects to MongoDB, You need to convert to dbobject objects, or directly implement the DBObject interface, which is very complex to operate. Fortunately, the Monodb drive with the ability to convert JSON into DBObject objects, plus Google's Gson, can be implemented to save ordinary objects to MongoDB. If you want to read the object from the Mogodb, in turn, but one thing to note is that MongoDB's document does not have a fixed field, so with gson conversion, it is possible that, because of the different document properties, the properties of the object being transferred are empty, making sure that the object of the same class is inserted at the time of insertion.
The following example inserts a user object into MongoDB and reads it
User.java:

 PackageCom.mongo; Public classUser {String name;intAge ; Oid _id;  PublicString GetName () {returnname;}  Public voidsetName (String name) { This. Name =name;}  Public intGetage () {returnAge ;}  Public voidSetage (intAge ) {   This. Age =Age ;} /*** MongoDB will automatically generate Objectid *@authorFHP **/  Public classoid{String $oid;  PublicString get$oid () {return$oid; }    Public voidset$oid (String $oid) { This. $oid =$oid; }  }}

Main.java:

 PackageCom.mongo;Importjava.net.UnknownHostException;ImportCom.google.gson.Gson;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;ImportCom.mongodb.DBObject;Importcom.mongodb.MongoClient;ImportCom.mongodb.util.JSON; Public classMain {/**  * @paramargs *@throwsunknownhostexception*/  Public Static voidMain (string[] args)throwsunknownhostexception {//TODO auto-generated Method StubMongoclient mongoclient =Newmongoclient (); DB Psdoc= Mongoclient.getdb ("Psdoc"); Dbcollection User=psdoc.getcollection ("User"); User U1=NewUser (); U1.setage (20); U1.setname ("SSSs"); Gson Gson=NewGson (); //convert to JSON string and convert to DBObject objectDBObject DBObject =(DBObject) json.parse (Gson.tojson (U1)); //Insert DatabaseUser.insert (dbobject); Dbcursor cursor=User.find ();  while(Cursor.hasnext ()) {DBObject obj=Cursor.next (); //reversalUser U=gson.fromjson (Obj.tostring (), user.class);     System.out.println (u.name); } } }

For convenience, you can directly integrate the Gson into the drive, directly modify the driver source code
Com.mongodb.DBCollection.java:
New method:

/**   * Write the normal object to the  database   *@param  obj  @return   */ public writeresult Insert (Object obj) {  new  Gson ();   = (dbobject) json.parse (Gson.tojson (obj));  Gson=null;   return Insert (dbobject);} Com.mongodb.DBCursor.java:

New method

/**      *     Read object from database @param  obj     @param  clazz     @return      */public     <T> T nextobj (class<t> clazz) {        _checktype ( Cursortype.iterator);        Gson Gson=new  Gson ();        T u=Gson.fromjson (_next (). toString (), clazz); Gson=null;         return u;    }

Modified Call Method:

Main.java: PackageCom.mongo;Importjava.net.UnknownHostException;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;Importcom.mongodb.MongoClient; Public classMain {/**  * @paramargs *@throwsunknownhostexception*/  Public Static voidMain (string[] args)throwsunknownhostexception {//TODO auto-generated Method StubMongoclient mongoclient =Newmongoclient (); DB Psdoc= Mongoclient.getdb ("Psdoc"); Dbcollection User=psdoc.getcollection ("User"); User U1=NewUser (); U1.setage (20); U1.setname ("SSSs"); //inserting objects directlyUser.insert (U1); Dbcursor cursor=User.find ();  while(Cursor.hasnext ()) {//passing in the class parameter back to the class objectUser u=cursor.nextobj (user.class);     System.out.println (u.name); } } }

Java Operation MongoDB Save/Read Java object to/from MongoDB

Related Article

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.