MongoDB -- Java encapsulation (ID auto-increment, gridfs)

Source: Internet
Author: User
Tags findone

Thomescai http://blog.csdn.net/thomescai (reprinted please keep)

Summary: MongoDB is encapsulated in Java to solve issues such as ID auto-increment and gridfs.

/*** Database interface ** @ author thomescai@163.com * @ version 2011-9-27 */public interface upload service {/*** upload object through gridfs * @ Param OBJ target object * @ Param paramsmap parameter Map * @ return * @ throws exception */Public Boolean gridfsupload (Object OBJ, hashmap <string, Object> paramsmap) throws exception;/*** Delete * @ Param paramsmap parameter map * @ return */Public Boolean gridfsdelete (hashmap <string, object> paramsmap);/*** insert dbobject object * @ Param idname the ID name of the object * @ Param dbobject the object * @ return */Public dbobject insert (string idname, dbobject);/*** get object * @ Param dbobject * @ return */Public dbobject getbyobj (dbobject ); /*** update data ** @ Param query the data object * @ Param OBJ update data * @ return */Public Boolean Update (dbobject query, dbobject OBJ ); /*** Delete object ** @ Param OBJ */Public void remove (dbobject OBJ );}

Public class implements serviceimpl implements Service {private string bucketname; private dB; Public implements serviceimpl (string dbname, string bucketname) {This. bucketname = bucketname; Mongo; try {Mongo = new Mongo ("192.168.17.28", 27017); this. DB = Mongo. getdb (dbname);} catch (unknownhostexception e) {e. printstacktrace ();} catch (except exception e) {e. printstacktrace () ;}}/*** upload an object through gridfs * @ par Am OBJ target object * @ Param paramsmap parameter map * @ return * @ throws exception */@ overridepublic synchronized Boolean gridfsupload (Object OBJ, hashmap <string, Object> paramsmap) throws ioexception {Boolean flag = false; gridfs = new gridfs (dB, bucketname); gridfsfile = NULL; If (OBJ instanceof inputstream) {gridfsfile = gridfs. createfile (inputstream) OBJ);} else if (OBJ instanceof byte []) {Grid Fsfile = gridfs. createfile (byte []) OBJ);} else if (OBJ instanceof file) {gridfsfile = gridfs. createfile (File) OBJ);} If (gridfsfile! = NULL & paramsmap! = NULL) {iterator iter = paramsmap. entryset (). iterator (); While (ITER. hasnext () {map. entry <string, Object> entry = (Entry <string, Object>) ITER. next (); gridfsfile. put (entry. getkey (), entry. getvalue ();} gridfsfile. save (); flag = true;} return flag ;} /*** use gridfs to delete * @ Param paramsmap parameter map * @ return */@ overridepublic synchronized Boolean gridfsdelete (hashmap <string, Object> paramsmap) {Boolean flag = f Alse; gridfs = new gridfs (dB, bucketname); dbobject query = new basicdbobject (); If (paramsmap! = NULL) {iterator iter = paramsmap. entryset (). iterator (); While (ITER. hasnext () {map. entry <string, Object> entry = (Entry <string, Object>) ITER. next (); query. put (entry. getkey (), entry. getvalue () ;}} dbobject OBJ = gridfs. findone (query); If (OBJ! = NULL) {gridfs. remove (OBJ); flag = true;} return flag ;} /*** insert dbobject object * @ Param idname ID name of the object * @ Param dbobject this object * @ return */@ overridepublic synchronized dbobject insert (string idname, dbobject) {INTEGER id = getautoincreaseid (idname); dbobject. put (idname, ID); getcollection (). insert (dbobject); Return dbobject;}/*** get connection * @ return */Public dbcollection getcollection () {return dB. getcollection (this. bucketname);}/*** obtain the connection according to the table name * @ Param name * @ return */Public dbcollection getcollection (string name) {return dB. getcollection (name);}/*** auto-increment ID * @ Param idname auto-increment ID name * @ return ID */Public integer getautoincreaseid (string idname) {basicdbobject query = new basicdbobject (); query. put ("name", idname); basicdbobject update = new basicdbobject (); update. put ("$ Inc", new basicdbobject ("ID", 1); dbobject dbobject2 = getcollection ("inc_ids "). findandmodify (query, null, null, false, update, true, true); integer id = (integer) dbobject2.get ("ID"); Return ID ;} /*** get object ** @ Param dbobject * @ return */@ overridepublic synchronized dbobject getbyobj (dbobject) {return getcollection (). findone (dbobject );} /*** update data ** @ Param query the data object * @ Param OBJ update data * @ return */@ overridepublic synchronized Boolean Update (dbobject query, dbobject OBJ) {writeresult rs = getcollection (). update (query, OBJ); Return (Boolean) rs. getfield ("updatedexisting") ;}@ overridepublic void remove (dbobject OBJ) {writeresult result = getcollection (). remove (OBJ );}}

Public class test {public static void main (string [] ARGs) {Alibaba service userdao = new Alibaba serviceimpl ("Account", "test"); system. out. println ("================ insert ==================== "); dbobject OBJ = new basicdbobject (); obj. put ("name", "AAA"); OBJ = userdao. insert ("test_id", OBJ); system. out. println ("================ get ================ "); dbobject objget = new basicdbobject (); objget. put ("name", "AAA"); objget = userdao. getbyobj (objget); system. out. println ("================ set ============== "); dbobject objadd = new basicdbobject (); objadd. put ("age2", "ag2444"); userdao. update (OBJ, new basicdbobject ("$ set", objadd); system. out. println ("================ set ================= "); dbobject objarrays = new basicdbobject (); objarrays. put ("arrays", new basicdbobject ("array1", "111"); userdao. update (OBJ, new basicdbobject ("$ push", objarrays); // userdao. remove (New basicdbobject ("test_id", 1 ));}}

Running result:

Table test:

Table inc_ids:

Note:

1. Record the IDs of each table in inc_ids. Each execution

DBObject dbObject2 = getCollection("inc_ids").findAndModify(query,null, null, false, update, true, true);

Implementation ID ++. Here, the built-in objectid of MongoDB is retained. You can also replace _ id with test_id directly.

2. Only simple encapsulation of update is implemented. There are also four update Methods:


The four methods are extended to DB. collection. Update (criteria, objnew, upsert, multi. Description:

Criteria: Query condition for update, similar to

Objnew: The update object and some updated operators (such as $, $ Inc...) can also be understood as

Upsert: this parameter indicates whether to insert objnew if no update record exists. True indicates insertion. The default value is false.

Multi: the default value of MongoDB is false. Only the first record found is updated. If this parameter is set to true, all the records identified by the condition are updated.

3. $ push, $ set, and so on are implemented in the form of a basicdbobject object, as follows:

DBObject objAdd = new BasicDBObject();objAdd.put("age2", "ag2444");userDAO.update(obj, new BasicDBObject("$set", objAdd));
userDAO.update(obj, new BasicDBObject("$push", objArrays));

Other commands can also be used.





References:

Bytes
Update Data syntax

Http://www.kafka0102.com/2011/03/435.html-- objecdbobjectid》


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.