Java Operation MongoDB Additions and deletions to check tool demo

Source: Internet
Author: User
Tags mongodb throwable

-Because of the internship needs, learning MongoDB, reference the company's a Mongdb service class, wrote a integrated demo, involved in most of the additions and deletions to check the operation, but also the norms, for you to reference. Source code: (Full project file download link: Click to open link) http://download.csdn.net/detail/zhangliangzi/9555872

Instructions for use:

First, MongoDB database parameter configuration

1, the recommended use of mongodb.cfg.properties configuration, the Mongodbservice object in the construction of the time only to call the parameterless construction method can automatically complete the configuration.


2. If the mongodb.cfg.properties is not passed, the default configuration specified by the program will be adopted.

Define default configuration, 1, IP address 2, port number 3, username 4, password 5, configuration file location name 6, database name
	private static final String mongodb_address = "127.0.0.1";
	private static final int mongodb_port = 27017;
	private static final String Mongodb_username = "root";
	private static final String Mongodb_password = "";
	private static final String Mongodb_resource_file = "Mongodb.cfg.properties";
	private static final String Mongodb_dbname = "Test";
	private static final String Mongodb_collectionname = "Test";

3, through the parameter construction method constructs the Mongodbservice object or through the Get/set method , specifies the database and the collection, the priority highest .

//a parametric constructor that specifies the database name and the collection name public Mongodbserviceimpl (String dbname, String collname) {this.dbname = dbname;
		This.collname = Collname;
		try {db = Getdb ();
		catch (Throwable e) {e.printstacktrace ();
	}//Parameterless constructor method, returns the database object reference for the configuration file configuration, and returns the default database object reference public Mongodbserviceimpl () {getdb () if there are no settings in the configuration file; * * * Get database objects, 3 cases (priority from high to low): <span style= "White-space:pre" > </span>*1, construction method specified 2, configuration file specified 3, default database <span Styl E= "White-space:pre" > </span>* (Conditions 2, 3 set in Mongodbutil) */public DB Getdb () {if (this.db = null) {if (thi
			S.dbname = = null) {this.db = Mongodbutil.getdb ();
			else {this.db = Mongodbutil.getdbbyname (this.dbname);
	} return this.db; * * * Get Collection Object, 3 cases (priority from high to low): * 1, construction method specified 2, configuration file specified 3, default database * (conditions 2, 3 set in Mongodbutil)/public dbcollection GE
		TCollection () {if (this.collname!= null) {return db.getcollection (this.collname);
		else {return mongodbutil.getdbcollection (); }
	}

Ii. Introduction of the method (see Mongodbserviceimpl interface implementation class for concrete implementation)

1. Get basic information or objects:

(1), get database name: Getdbname ()
(2), set database name (Specify database): Setdbname (String dbname)
(3), get the collection name: Getcollname ()
(4), set the name of the collection (Specify the collection): Setcollname (String collname)
(5), Get database objects: Getdb ()

2, the data inserts the way:
(1) Inserting a single piece of data: Insert (DBObject obj)
(2) inserting multiple data: Insertbatch (list<dbobject> List) void

3. Data deletion way:
(1), delete a single data: delete (DBObject obj)
(2), delete more than one data: Deletebatch (list<dbobject> List)

4, the number of statistical methods:
(1), get the number of data in the collection: Getcollectioncount ()
(2), obtain the number of eligible data: GetCount (DBObject obj)

5. Find data:
(1), Find all data: FindAll ()
(2), find the Eligible data: found (DBObject obj)
(3), find the eligible data and sort: found (dbobject query, dbobject sort)
(4), find the specified amount of data to match the criteria and sort: found (dbobject query, dbobject sort, int start, int limit)
(5), find data by ID: GetByID (String ID)

6, update the data:Update (DBObject setfields, dbobject wherefields) void

7, print List<dbobject>:Printlistdbobj (list<dbobject> List)

Test Code: (@Test)

public class Testmongoservice {//using the database and collection configured in Mongodb.cfg.properties, if unspecified, use the default database and collection in Mongodbutil Mongodbservice
	
	MongoDBService1 = new Mongodbserviceimpl ();
		Test Insert Data @Test public void Testinsert () {//data one, including username, password, address information (province, city), hobby [...]
		Basicdblist dbList1 = new Basicdblist ();
		Dblist1.add ("basketball");
		Dblist1.add ("Music");
		Dblist1.add ("Web"); DBObject DbObject1 = new Basicdbobject ("username", "Insert1"). Append ("Age",). Append ("Address", new Basicdbobject
		("Province", "Guangdong"). Append ("City", "Guangzhou")). Append ("favourite", DbList1);
		Data two basicdblist dbList2 = new Basicdblist ();
		Dblist2.add ("football");
		Dblist2.add ("Music"); DBObject dbObject2 = new Basicdbobject ("username", "Insert2"). Append ("Age",). Append ("Address", new Basicdbobject
		("Province", "Shaanxi"). Append ("City", "Xian")). Append ("favourite", DbList2);
		Data three basicdblist dbList3 = new Basicdblist ();
		Dblist3.add ("Linux"); DBObject dbObject3 = new Basicdbobject ("username", "INSERT3"). APPend ("Age"). Append ("Address", New Basicdbobject ("Province", "Hebei"). Append ("City", "Baoding")). Append ("Favourite", Dbl
		IST3);
		Data four basicdblist dbList4 = new Basicdblist ();
		Dblist4.add ("Swim");
		Dblist4.add ("Android"); DBObject DbObject4 = new Basicdbobject ("username", "Insert4"). Append ("Age",). Append ("Address", new Basicdbobject
		("Province", "Sichuan"). Append ("City", "Chengdu")). Append ("favourite", DbList4); Data five DBObject dbObject5 = new Basicdbobject ("username", "Insert5"). Append ("Age"). Append ("Address", New Basi
		Cdbobject ("City", "Hangzhou"));
		Mongodbservice1.printlistdbobj (Mongodbservice1.findall ());
		System.out.println ("—————————————————— Insert Collection ——————————————————");
		list<dbobject> list = new arraylist<dbobject> ();
		List.add (DBOBJECT1);
		List.add (DBOBJECT2);
		List.add (DBOBJECT3);
		List.add (DBOBJECT5);
		Mongodbservice1.insertbatch (list);
		System.out.println ("—————————————————— insert one ——————————————————"); Mongodbservice1.iNsert (DBOBJECT4);
	Mongodbservice1.printlistdbobj (Mongodbservice1.findall ());
		///test query data @Test public void Testfind () {dbobject dbobject = new Basicdbobject ("username", "insert1");
		System.out.println ("Quantity:" + mongodbservice1.getcollectioncount ());
		System.out.println ("Username=java Number of data:" + mongodbservice1.getcount (dbobject));
		System.out.println ("—————————————————— Find All ——————————————————");
		Mongodbservice1.printlistdbobj (Mongodbservice1.findall ());
		System.out.println ("—————————————————— find obj ——————————————————");
		Mongodbservice1.printlistdbobj (Mongodbservice1.find (dbobject));
		System.out.println ("—————————————————— find sort ——————————————————");
		Mongodbservice1.printlistdbobj (Mongodbservice1.find (New Basicdbobject (), New Basicdbobject ("Age", 1));
		System.out.println ("—————————————————— Find sort limit ——————————————————");
	Mongodbservice1.printlistdbobj (Mongodbservice1.find) (New Basicdbobject (), New Basicdbobject ("Age", 1), 1, 2); }//test Data Update @Test public void Testupdate () {basicdbobject newdocument = new Basicdbobject ("$set", New Basicdbobject ("Age", 11);
	
		Basicdbobject searchquery = new Basicdbobject (). Append ("username", "insert2");
		Mongodbservice1.printlistdbobj (Mongodbservice1.find (searchquery));
		SYSTEM.OUT.PRINTLN ("—————————————————— update ——————————————————");
		Mongodbservice1.update (NewDocument, searchquery);
	Mongodbservice1.printlistdbobj (Mongodbservice1.find (searchquery));
		}//test data deletion @Test public void Testdelete () {dbobject dbObject1 = new Basicdbobject ("username", "insert1");
		DBObject dbObject2 = new Basicdbobject ("username", "insert2");
		DBObject dbObject3 = new Basicdbobject ("username", "insert3");
		DBObject DbObject4 = new Basicdbobject ("username", "insert4");
		DBObject dbObject5 = new Basicdbobject ("username", "insert5");
		list<dbobject> list = new arraylist<dbobject> ();
		List.add (DBOBJECT1);
		List.add (DBOBJECT2);
		List.add (DBOBJECT3);
		List.add (DBOBJECT4); Mongodbservice1.prIntlistdbobj (Mongodbservice1.findall ());
		System.out.println ("—————————————————— Delete list ——————————————————");
		Mongodbservice1.deletebatch (list);
		System.out.println ("—————————————————— Delete one ——————————————————");
		Mongodbservice1.delete (DBOBJECT5);
		System.out.println ("—————————————————— Delete all ——————————————————");
		Mongodbservice1.delete (New Basicdbobject ());
	Mongodbservice1.printlistdbobj (Mongodbservice1.findall ()); }
}
Test Results:





Source code:(full project file download link: Click to open the link)

Mongodbserviceimpl.java

public class Mongodbserviceimpl implements Mongodbservice {private String dbname;
	Private String Collname;
	
	private DB DB;
		A parameter constructor method that specifies the database name and the collection name public Mongodbserviceimpl (String dbname, String collname) {this.dbname = dbname;
		This.collname = Collname;
		try {db = Getdb ();
		catch (Throwable e) {e.printstacktrace ();
	}//Parameterless constructor method, returns the database object reference for the configuration file configuration, and returns the default database object reference public Mongodbserviceimpl () {getdb () if there are no settings in the configuration file; * * * Get database objects, 3 cases (priority from high to low): * 1, construction method specified 2, configuration file specified 3, default database * (conditions 2, 3 set in Mongodbutil)/public DB Getdb () {if T
			His.db = = null) {if (this.dbname = = null) {this.db = Mongodbutil.getdb ();
			else {this.db = Mongodbutil.getdbbyname (this.dbname);
	} return this.db; * * * Get Collection Object, 3 cases (priority from high to low): * 1, construction method specified 2, configuration file specified 3, default database * (conditions 2, 3 set in Mongodbutil)/public dbcollection Getcol
		Lection () {if (this.collname!= null) {return db.getcollection (this.collname);
		else {return mongodbutil.getdbcollection ();
	}Public DBObject map2obj (map<string, object> Map) {dbobject obj = new Basicdbobject ();
		if (Map.containskey ("class") && Map.get ("Class") Instanceof Class) Map.Remove ("class");
		Obj.putall (map);
	return obj;
	//Insert data public void Insert (DBObject obj) {getcollection (). Insert (obj);
		}//Insert multiple data public void Insertbatch (list<dbobject> list) {if (list = = NULL | | list.isempty ()) {return;
		} list<dbobject> Listdb = new arraylist<dbobject> ();
		for (int i = 0; i < list.size (); i++) {Listdb.add (List.get (i));
	} getcollection (). Insert (LISTDB);
	}//delete data public void Delete (DBObject obj) {getcollection (). Remove (obj);
		}//delete multiple data public void Deletebatch (list<dbobject> list) {if (list = = NULL | | list.isempty ()) {return;
		for (int i = 0; i < list.size (); i++) {getcollection (). Remove (List.get (i));
	//Gets the number of data in the collection public long Getcollectioncount () {return getcollection (). GetCount (); }//Find eligibleThe number of data public long GetCount (DBObject obj) {if (obj!= null) return GetCollection (). GetCount (obj);
	return Getcollectioncount ();
		///Find the Eligible data public list<dbobject> found (DBObject obj) {dbcursor cur = getcollection (). finding (obj);
	return dbcursor2list (cur);
		//Find eligible data and sort @Override public list<dbobject> found (dbobject query, dbobject sort) {dbcursor cur;
		if (query!= null) {cur = getcollection (). Find (query);
		else {cur = getcollection (). find ();
		} if (sort!= null) {cur.sort (sort);
	return dbcursor2list (cur); //Find eligible data and sort, specify the number of data @Override public list<dbobject> found (dbobject query, dbobject sort, int start, int li
		MIT) {dbcursor cur;
		if (query!= null) {cur = getcollection (). Find (query);
		else {cur = getcollection (). find ();
		} if (sort!= null) {cur.sort (sort);
		} if (start = = 0) {cur.batchsize (limit);
		else {cur.skip (start). limit (limit);
	return dbcursor2list (cur);
	
	}Convert dbcursor to list<dbobject> private list<dbobject> dbcursor2list (dbcursor cur) {list<dbobject>
		List = new arraylist<dbobject> ();
		if (cur!= null) {list = Cur.toarray ();
	} return list; }//Update data public void update (DBObject setfields, DBObject wherefields) {getcollection (). Updatemulti (Wherefields, SETF
	Ields);
		}///query collection all data public list<dbobject> FindAll () {dbcursor cur = getcollection (). find ();
		list<dbobject> list = new arraylist<dbobject> ();
		if (cur!= null) {list = Cur.toarray ();
	} return list;
		///ID Get Data public dbobject GetByID (String id) {DBObject obj = new Basicdbobject ();
		Obj.put ("_id", new ObjectId (ID));
		DBObject result = GetCollection (). FindOne (obj);
	return result;
	Public String Getdbname () {return dbname;
		} public void Setdbname (String dbname) {this.dbname = dbname;
	This.db = Mongodbutil.getdbbyname (this.dbname);
	Public String Getcollname () {return collname;

}	public void Setcollname (String collname) {this.collname = Collname; @Override the public void Printlistdbobj (list<dbobject> List) {//TODO auto-generated a stub for (dbobject
		Dbobject:list) {System.out.println (dbobject);
 }
	}

	

}
Mongodbutil.java

public class Mongodbutil {//define default configuration, 1, IP address 2, port number 3, username 4, password 5, profile location name 6, database name private static final String Mongodb_addres
	S = "127.0.0.1";
	private static final int mongodb_port = 27017;
	private static final String Mongodb_username = "root";
	private static final String Mongodb_password = "";
	private static final String Mongodb_resource_file = "Mongodb.cfg.properties";
	private static final String Mongodb_dbname = "Test";
	private static final String Mongodb_collectionname = "Test";
	Define static variables, 1, Mongo objects (for database connections) 2, DB objects (on behalf of database) 3, set name 4, database-related configuration Mapping set 5, acquired database connection private static Mongo Mongo;
	private static DB db;
	private static Dbcollection collection;
	private static map<string, string> Cfgmap = new hashmap<string, string> ();

	private static hashtable<string, db> Mongodbs = new hashtable<string, db> ();
	/** * Initialize the MONGO database */static {init ();
	/** * Gets the DB object configured in the configuration file */public static DB Getdb () {return db; /** * Get the Dbcollection object configured in the config file */PUblic static Dbcollection getdbcollection () {return collection; /** * According to the database name, get the database if it does not exist, create a database of that name and set the username and password as the parameter value in the profile * * @param dbname * @return DB * * * * @SuppressWarn
		Ings ("deprecation") public static DB Getdbbyname (String dbname) {db db = Mongo.getdb (dbname);
			if (!mongodbs.contains (db)) {System.out.println ("add");
			Db.adduser (Cfgmap.get ("Mongo.db.username"), Cfgmap.get ("Mongo.db.password"). ToCharArray ());
		Mongodbs.put (dbname, DB);
	} return DB; }//———————————————————————————————————— initialization process ————————————————————————————————————/** * Gets the file object for profile mongedb.cfg.properties/public static file Getconfigfile () {String path = MongoDBUtil.class.getResource
		("/"). GetPath ();
		String fileName = path + mongodb_resource_file;
		System.out.println (FileName);
		File File = new file (fileName);
		if (file.exists ()) {return file;
	return null; /** * Initializes the configuration mapping collection through the Mongedb.cfg.properties configuration file, and if no configuration file is written, the default configuration specified by the loader is * * * @SuppressWarninGS ("unchecked") private static void Initcfgmap () {File file = Getconfigfile ();
			if (file!= null) {Properties P = new properties ();
				try {p.load (new FileInputStream (file)); For (Enumeration ENU = P.propertynames (); enu.hasmoreelements ();)
					{String key = (string) enu.nextelement ();
					String value = (string) p.getproperty (key);
				Cfgmap.put (key, value);
				The catch (IOException e) {System.out.println ("Failed to load MONGO configuration file!");
			E.printstacktrace ();
			} else {//If no configuration file is written, load the default configuration Cfgmap.put ("Mongo.db.address", mongodb_address);
			Cfgmap.put ("Mongo.db.port", String.valueof (Mongodb_port));
			Cfgmap.put ("Mongo.db.username", mongodb_username);
			Cfgmap.put ("Mongo.db.password", Mongodb_password);
			Cfgmap.put ("Mongo.db.dbname", mongodb_dbname);
		Cfgmap.put ("Mongo.db.collectionname", mongodb_collectionname); }/** * Initializes the MONGO database (points the DB to the corresponding object reference, points collection to the corresponding object reference, records the existing database object through Mongodbs)/@SuppressWarnings ("deprecation") p Rivate static void Init () {initcfgmap ();
			try {String address = Cfgmap.get ("mongo.db.address");
			int port = integer.parseint (Cfgmap.get ("Mongo.db.port"). toString ());
			String dbname = Cfgmap.get ("Mongo.db.dbname");
			String username = cfgmap.get ("Mongo.db.username");
			String Password = cfgmap.get ("Mongo.db.password");
			String CollectionName = Cfgmap.get ("Mongo.db.collectionname");
			MONGO = new MONGO (address, Port); if (dbname!= null &&! "".
				Equals (dbname)) {db = Mongo.getdb (dbname); if (username!= null &&! "".
					Equals (username)) {db.adduser (username, Password.tochararray ()); if (CollectionName!= null &&! "".
					Equals (CollectionName)) {collection = Db.getcollection (CollectionName);
			} mongodbs.put (dbname, DB);
		} catch (Exception e) {e.printstacktrace ();
 }
	}

}


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.