Java Operations MongoDB Save/Read Java objects to/from MongoDB

Source: Internet
Author: User
Tags json mongoclient mongodb mongodb save stub tojson

MongoDB official Java driver, save and read, the need is DBObject object, this is an interface, implementation put,get and other methods, similar to map, if we want to directly save ordinary Java objects to MongoDB, It needs to be converted into DBObject object first, or implement DBObject interface directly, it is quite complicated to operate. Fortunately, the Monodb drive with the ability to convert JSON to dbobject objects, plus Google's Gson, can be implemented to save ordinary objects to MongoDB. If you want to read an object from the Mogodb, conversely, it is important to note that the MongoDB document does not have a fixed field, so use the Gson conversion, because each document property is different, the object property that is turned out is empty, to make sure that the object that inserts the same class is inserted.
The following example inserts a user object into the MongoDB and reads it
User.java:

The code is as follows Copy Code

Package Com.mongo;

public class User {
String name;
int age;
Oid _id;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
/**
* MongoDB will automatically generate Objectid
* @author FHP
*
*/
public class oid{
String $oid;
Public String get$oid () {
return $oid;
}

public void Set$oid (String $oid) {
this. $oid = $oid;
}

}
}

Main.java:

The code is as follows Copy Code

Package Com.mongo;

Import java.net.UnknownHostException;

Import Com.google.gson.Gson;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import com.mongodb.MongoClient;
Import Com.mongodb.util.JSON;

public class Main {

/**
* @param args
* @throws unknownhostexception
*/
public static void Main (string[] args) throws Unknownhostexception {
TODO auto-generated Method Stub
Mongoclient mongoclient = new Mongoclient ();

DB Psdoc = Mongoclient.getdb ("Psdoc");
Dbcollection user=psdoc.getcollection ("user");

User U1=new user ();
U1.setage (20);
U1.setname ("SSSs");
Gson gson=new Gson ();
Convert to JSON string, then convert to DBObject object
DBObject dbobject = (dbobject) json.parse (Gson.tojson (U1));
Insert Database
User.insert (DBObject);

Dbcursor Cursor=user.find ();
while (Cursor.hasnext ())
{
DBObject Obj=cursor.next ();
Reverse
User U=gson.fromjson (obj.tostring (), user.class);
System.out.println (u.name);
}
}

}

In order to facilitate, you can directly integrate the Gson into the drive, directly modify the driving source code
Com.mongodb.DBCollection.java:
New methods:

The code is as follows Copy Code

/**
* Write common objects to the database
*
* @param obj
* @return
*/
Public writeresult Insert (Object obj) {
Gson Gson = new Gson ();
DBObject dbobject = (dbobject) json.parse (Gson.tojson (obj));
Gson=null;
return insert (DBObject);
}

Com.mongodb.DBCursor.java:

New methods

The code is as follows Copy Code

/**
* Read the object from the 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 method of invocation:

The code is as follows Copy Code

Main.java:

Package Com.mongo;

Import java.net.UnknownHostException;

Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import com.mongodb.MongoClient;

public class Main {

/**
* @param args
* @throws unknownhostexception
*/
public static void Main (string[] args) throws Unknownhostexception {
TODO auto-generated Method Stub
Mongoclient mongoclient = new Mongoclient ();

DB Psdoc = Mongoclient.getdb ("Psdoc");
Dbcollection user=psdoc.getcollection ("user");

User U1=new user ();
U1.setage (20);
U1.setname ("SSSs");
Insert Object directly
User.insert (U1);
Dbcursor Cursor=user.find ();
while (Cursor.hasnext ())
{
Pass in the class parameter, back to the class object
User u=cursor.nextobj (User.class);
System.out.println (u.name);
}
}

}

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.