Java connection, manipulating MongoDB

Source: Internet
Author: User
Tags throw exception

Java Connection MongoDB is very simple, specifically 2 steps:
1: Import the Java-mongo driver package to the new project
:

2: Create a link helper class to complete the link operation

Packagecom. YC. MongoDB;Import Java. Util. Iterator;Import Java. Util. Set;Importcom. MongoDB. Basicdbobject;Importcom. MongoDB. DB;Importcom. MongoDB. Dbcollection;Importcom. MongoDB. Dbcursor;Importcom. MongoDB. DBObject;Importcom. MongoDB. Mongo;Importcom. MongoDB. Writeresult;public class MongoLink2 {public static void main (string[] args) {Mongo mongo=null;DB Db=null;try {//link MONGO Server Mongo=new MONGO ("127.0.0.1",27017);DB objects are obtained from the name of the MongoDB database, and the database is connected to YC Db=mongo. Getdb("YC");Send GET Request db. Requeststart();Get its collectionSet<String> collections=db. Getcollectionnames();Iterator itr=collections. Iterator();Iterate output information while (ITR. Hasnext()) {System. out. println(ITR. Next());} dbcollection dbobject=db. GetCollection("YC");DBObject Object=null;Add Object=new basicdbobject ();Object. Put("_id",1003);Object. Put("Name","Zhang San");Object. Put("Sex","Male");Writeresult Rs=dbobject. Insert(object);Object. Put("_id",1002);Remove DBObject. Remove(New Basicdbobject ());Find All Dbcursor Cursor=dbobject. Find();while (cursor. Hasnext()) {Object=cursor. Next();System. out. println(object);}} catch (Exception e) {E. Printstacktrace();}finally{if (mongo!=null) {MONGO. Close();}        }    }}

The results of the operation are as follows:

At this point, actually already can use, the code coupling is too high, the function bundle is too serious, inconvenient to call,
It is then encapsulated.

Define a property file first:

It defines some basic configuration, such as user name, database name, IP, port, etc.
Next, define a class to read its files. The document is best defined as a singleton,

 PackageCom.yc.mongodb;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.util.Properties;@SuppressWarnings("Serial") Public  class mypro extends Properties{    Private StaticMypro instanece=NewMypro ();Private Mypro() {InputStream Is=mypro.class.getresourceasstream ("/db.properties");Try{ This. Load (IS); }Catch(IOException e)        {E.printstacktrace (); }finally{if(is!=NULL){Try{Is.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }    } Public StaticMyprogetinstance(){returnInstanece; }}

Define a DBHelper class like Oracle to enable encapsulation of data operations:
As follows:

 PackageCom.yc.mongodb;ImportJava.net.UnknownHostException;ImportCom.mongodb.DB;ImportCom.mongodb.DBCollection;ImportCom.mongodb.Mongo;ImportCom.mongodb.MongoException; Public  class dbhelper {    Private StaticMongo mongo=NULL;PrivateDB db=NULL;PrivateDbcollection collection=NULL;Static{Try{mongo=NewMongo (Mypro.getinstance (). GetProperty ("IP"), Integer.parseint (Mypro.getinstance (). GetProperty ("Port"))); }Catch(NumberFormatException e)            {E.printstacktrace (); }Catch(Unknownhostexception e)            {E.printstacktrace (); }Catch(Mongoexception e)            {E.printstacktrace ();    } System.out.println (MONGO); }/** * * @param dbName * @param name * @param pwd * @return */     Public Boolean Getdb(String dbname,string name,string pwd) {Db=mongo.getdb (dbName);if(name!=NULL&&!"". Equals (name) &&pwd!=NULL&&!"". Equals (PWD) {if(Db.authenticate (name, Pwd.tochararray ())) {return true; }Else{return false; }        }Else{//See if a user name and password are given in the configuration fileString uname=mypro.getinstance (). GetProperty ("Uname"); String pwds=mypro.getinstance (). GetProperty ("Password");if(uname!=NULL&&!"". Equals (uname) &&pwds!=NULL&&!"". Equals (PWDs)) {if(Db.authenticate (uname, Pwds.tochararray ())) {return true; }Else{return false; }            }        }return true; }/** * Close connection * @param MONGO */     Public void CloseAll(Mongo Mongo) {if(mongo!=NULL) {mongo.close (); }    }}//using method overloading to implement different cases of the parameters/** * Gets the specified collection * @param CollectionName: The collection to be linked * @param dbName: The database where the collection resides * @return      */     PublicDbcollectiongetdbcollection(String collectionname,string DbName) {dbcollection dbcollection=NULL;if(Getdb (DbName,NULL,NULL)) {Db.requeststart ();if(collectionname==NULL){//If empty, look in the configuration fileCollectionname=mypro.getinstance (). GetProperty ("CollectionName");        } dbcollection=db.getcollection (CollectionName); }Else{//Throw exception            Throw NewRuntimeException ("Database connection Failed"); }returnDbcollection; }/** * * @param collectionname * @param dbName * @param name * @par AM Password * @return * *     PublicDbcollectiongetdbcollection(String collectionname,string dbname,string name,string password) {dbcollection dbcollection=NULL;if(Getdb (dbname,name, password)) {Db.requeststart ();if(collectionname==NULL){//If empty, look in the configuration fileCollectionname=mypro.getinstance (). GetProperty ("CollectionName");        } dbcollection=db.getcollection (CollectionName); }Else{//Throw exception            Throw NewRuntimeException ("Database connection Failed"); }returnDbcollection; }/** * Only Pass collection name * @param collectionname * @return * *     PublicDbcollectiongetdbcollection(String CollectionName) {dbcollection dbcollection=NULL; String dbname=mypro.getinstance (). GetProperty ("DbName");if(Getdb (DbName,NULL,NULL)) {Db.requeststart ();if(collectionname==NULL){//If empty, look in the configuration fileCollectionname=mypro.getinstance (). GetProperty ("CollectionName");        } dbcollection=db.getcollection (CollectionName); }Else{//Throw exception            Throw NewRuntimeException ("Database connection Failed"); }returnDbcollection; }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java connection, manipulating 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.