Java Operations MongoDB Database sample sharing _mongodb

Source: Internet
Author: User
Tags mongodb reserved

MongoDB is a document-type database, one of the most important members of the NoSQL family, and the following code encapsulates the basic operations of MongoDB.

Mongodbconfig.java

Package Com.posoftframework.mongodb;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import java.util.Enumeration;
Import Java.util.HashMap;
Import java.util.Hashtable;
Import java.util.List;
Import Java.util.Map;
Import java.util.Properties;
Import Com.mongodb.DB;
Import Com.mongodb.Mongo;
  /** * MONGODB Configuration class * * @author yongtree * @date 2010-7-7 PM 07:45:08 * @version 1.0/public class Mongodbconfig {
  private static Mongo Mongo;
  private static DB db;
  private static final String mongo_db_address = "localhost";
  private static final int mongo_db_port = 27017;
  private static final String Mongo_db_username = "root";
  private static final String Mongo_db_password = "root";
  private static final String Mongo_db_dbname = "MongoDB";
  private static final String Mongo_db_resource_file = "Mongodb.cfg.properties";
  /** * MONGO Database parameters * * 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 ();
    public static File Getconfigfile () {String path = MongoDBConfig.class.getResource ("/"). GetPath ();
    String fileName = path + mongo_db_resource_file;
    File File = new file (fileName);
    if (file.exists ()) {return file;
  return null;
    @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);
        catch (IOException e) {System.out.println ("Chronicle MONGO config file failed!");
      E.printstacktrace (); } else {cfgmap.put ("MONGO.DB.ADdress ", mongo_db_address);
      Cfgmap.put ("Mongo.db.port", String.valueof (Mongo_db_port));
      Cfgmap.put ("Mongo.db.username", mongo_db_username);
      Cfgmap.put ("Mongo.db.password", Mongo_db_password);
    Cfgmap.put ("Mongo.db.dbname", mongo_db_dbname);
    }/** * Initializes the MONGO database */private 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");
      MONGO = new MONGO (address, Port); if (dbname!= null &&! "".
        Equals (dbname)) {db = Mongo.getdb (dbname); if (username!= null &&! "".
        Equals (username)) {db.adduser (username, Password.tochararray ());
      } mongodbs.put (dbname, DB); The catch (IOException e) {e). Printstacktrace ();
  }/** * Get Mongo Instance * * @return/public static Mongo Getmongo () {return Mongo;
  /** * Get MONGO Image Database * * @return/public static DB Getdb () {return db;
  public static list<string> Getdbnames () {return mongo.getdatabasenames ();  /** * According to database name, get database <br/> * If not present, create a database of that name and set the username and password as parameter values in the configuration file </br> * * @param dbname *
    @return */public static DB Getdbbyname (String dbname) {db db = Mongo.getdb (dbname); if (!mongodbs.contains (db)) {Db.adduser (Cfgmap.get ("Mongo.db.username"), Cfgmap.get ("Mongo.db.password")
      . ToCharArray ());
    Mongodbs.put (dbname, DB);
  } return DB;

 }
}

Mongoservice.java

/************************* Copyright Notice ********************************* * * All rights reserved: Hundred Ocean Software * * Copyright (c) by WWW.P o-soft.com * * * ****************** 
 Change Record ********************************* * Creator: yongtree Date Created: 2010-7-7 * NOTE: * * Modified By: * Note: *
* * Package com.posoftframework.mongodb;
Import java.util.List;
Import Java.util.Map;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBObject; /** * Operation MongoDB DAO interface * * @author yongtree * @date 2010-7-7 PM 04:44:43 * @version 1.0 * * Public interface Mongoserv
  Ice {public abstract dbcollection getcollection (); /** * According to the map of the data set, insert the key value of the dbcollection in the key corresponding database of the data map * * @param obj/public abstract dbobject Insert (DBO
  Bject obj); /** * According to List<map<stRing,object>> structure data collection, inserting data * * @param list/public abstract void Insertbatch (list<dbobject> list)
  ;
  /** * Set map with conditional parameters, delete data * * @param map */public abstract void Delete (DBObject obj);
  /** * According to the combination of various conditions, bulk delete data * * @param list/public abstract void Deletebatch (list<dbobject> list);
  /** * Get Collection () total number of records * * @return/public abstract long getcollectioncount ();
  Public abstract long GetCount (dbobject query);
  Public abstract list<dbobject> Find (dbobject query);
  Public abstract list<dbobject> Find (dbobject query,dbobject sort);
  Public abstract list<dbobject> Find (dbobject query,dbobject sort,int start,int limit); /** * Update setfields value * @param setfields * @param wherefields/public abstract void upd based on wherefields parameters
  Ate (DBObject setfields, DBObject wherefields);
  Public abstract list<dbobject> findall (); /** * Find unique data based on ID 1 ID field tags * * @parAM ID * @return/public abstract dbobject GetByID (String ID);
  /** * Get ALL database name * * @return/public list<string> getalldbnames ();
  Public abstract String getdbname ();
  public abstract void Setdbname (String dbname);
  Public abstract DB getdb ();
  Public abstract String getcollname ();
public abstract void Setcollname (String collname);

 }

Mongoserviceimpl.java

/************************* Copyright Notice ********************************* * * All rights reserved: Hundred Ocean Software * * Copyright (c) by WWW.P o-soft.com * * * ****************** 
 Change Record ********************************* * Creator: yongtree Date Created: 2010-7-7 * NOTE: * * Modified By: * Note: *
* * Package com.posoftframework.mongodb;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Map;
Import Org.bson.types.ObjectId;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject; /** * * @author yongtree * @date 2010-7-7 Afternoon 07:22:15 * @version 1.0/public class Mongoserviceimpl implements Mong
  Oservice {private String dbname;
  Private String Collname;
  private DB DB; Public MongoserViceimpl (String dbname, String collname) {this.dbname = dbname;
    This.collname = Collname;
    try {db = Mongodbconfig.getdbbyname (this.dbname);
    catch (Throwable e) {e.printstacktrace ();
  } public Mongoserviceimpl () {getdb ();
  Public Dbcollection GetCollection () {return db.getcollection (this.collname);
    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;
    Public dbobject Insert (DBObject obj) {getcollection (). Insert (obj);
  return obj;
    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);
  public void Delete (DBObject obj) {getcollection (). Remove (obj);
    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));
  } public Long Getcollectioncount () {return getcollection (). GetCount ();
    Public long GetCount (DBObject obj) {if (obj!= null) return GetCollection (). GetCount (obj);
  return Getcollectioncount ();
    list<dbobject> find (DBObject obj) {dbcursor cur = getcollection (). find (obj);
  return dbcursor2list (cur);
    @Override public list<dbobject> Find (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); } @Override Public list<dbobject>Find (dbobject query, dbobject sort, int start, int limit) {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); Private list<dbobject> dbcursor2list (dbcursor cur) {list<dbobject> List = new ARRAYLIST&LT;DBOBJECT&G
    t; ();
    if (cur!= null) {list = Cur.toarray ();
  } return list; } public void Update (DBObject setfields, DBObject wherefields) {getcollection (). Updatemulti (Setfields, Wherefields)
  ;
    Public list<dbobject> FindAll () {dbcursor cur = getcollection (). find ();
    list<dbobject> list = new arraylist<dbobject> ();
    if (cur!= null) {list = Cur.toarray ();
  } return list; 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 = Mongodbconfig.getdbbyname (this.dbname);
  Public String Getcollname () {return collname;
  } public void Setcollname (String collname) {this.collname = Collname; The public DB Getdb () {if (this.db = = null) {if (This.dbname = null) {this.db = Mongodbconfig.getdb (
      );
      else {this.db = Mongodbconfig.getdbbyname (this.dbname);
  } return this.db;
  Public list<string> Getalldbnames () {return mongodbconfig.getdbnames ();
 }
}

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.