| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
efx4
9年前发布

java操作mongoDB实现CURD

java操作mongoDB
mongoDB作为一个牛气哄哄的nosql内存数据库,的确有很多优点,对于大数据量、高并发、弱事务的互联网应用,MongoDB可以应对自如。接触 到mongoDB 参考了下api实现了增删改查、mongoDB 是面向对象设计,不用写sql语句 直接操作api 方法 就可以实现,这会儿数据库语句写不好的娃娃们有福了。直接贴码:

DataTest.java

package com.zk.db;  import java.net.UnknownHostException;  import java.util.ArrayList;  import java.util.List;  import org.bson.types.ObjectId;  import org.junit.Test;  import com.mongodb.BasicDBObject;  import com.mongodb.DB;  import com.mongodb.DBCollection;  import com.mongodb.DBCursor;  import com.mongodb.DBObject;  import com.mongodb.Mongo;  import com.mongodb.MongoException;  /**   * 测试mongodb curd   * @author zk   * @time   2015年4月24日23:19:15   */  public class DataTest {      // 1.建立一个Mongo的数据库连接对象      static Mongo connection = null;      // 2.创建相关数据库的连接      static DB db = null;        static {          try {              connection = new Mongo("127.0.0.1:27017"); //默认链接地址          } catch (Exception e) {              e.printStackTrace();          }          db = connection.getDB("one");//获取数据库名称      }        /**       * 测试创建数据文档集合 类似 数据表 person       * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test1() throws UnknownHostException, MongoException {          // 实例化          MongoDb mongoDb = new MongoDb("one");          mongoDb.createCollection("person");        }        /**       * 测试添加一条记录       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test2() throws UnknownHostException, MongoException {          // 实例化          DBObject p1 = new BasicDBObject();          p1.put("name", "zk00");          insert(p1, "person");        }        /**       * 测试添加一条记录       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test3() throws UnknownHostException, MongoException {          List<DBObject> dbObjects = new ArrayList<DBObject>();          DBObject zs = new BasicDBObject("name", "zhaosi");          DBObject zq = new BasicDBObject("name", "zhuqi");          dbObjects.add(zs);          dbObjects.add(zq);          insertBatch(dbObjects, "person");        }        /**       * 测试 根据id 删除一条记录       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test4() throws UnknownHostException, MongoException {            deleteById("553a5accb9d133bcf4056a40", "person");        }        /**       * 测试 根据条件 删除       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test5() throws UnknownHostException, MongoException {            DBObject obj = new BasicDBObject();          obj.put("name", "zk00");          int count = deleteByDbs(obj, "person");          System.out.println("删除数据的条数是: " + count);      }        /**       * 测试 更新操作       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test6() throws UnknownHostException, MongoException {          DBObject obj = new BasicDBObject();          obj.put("name", "zhaosi");          DBObject update = new BasicDBObject();          update.put("$set", new BasicDBObject("name", "nn1"));          update(obj, update, false, true, "person");      }        /**       * 测试 查询出person集合中的name       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test7() throws UnknownHostException, MongoException {          DBObject keys = new BasicDBObject();          keys.put("_id", false);          keys.put("name", true);          DBCursor cursor = find(null, keys, "person");          while (cursor.hasNext()) {              DBObject object = cursor.next();              System.out.println(object.get("name"));          }      }        /**       * 测试 分页       *        * @throws UnknownHostException       * @throws MongoException       */      @Test      public void test8() throws UnknownHostException, MongoException {          DBCursor cursor = find(null, null, 0, 6, "person");          while (cursor.hasNext()) {              DBObject object = cursor.next();              System.out.print("name=" + object.get("name") + "  ");              System.out.println("_id=" + object.get("_id"));            }      }        /**       * 创建一个数据库集合       *        * @param collName       *            集合名称       * @param db       *            数据库实例       */      public void createCollection(String collName) {          DBObject dbs = new BasicDBObject();          db.createCollection("person", dbs);      }        /**       * 为相应的集合添加数据       *        * @param dbs       * @param collName       */      public void insert(DBObject dbs, String collName) {          // 1.得到集合          DBCollection coll = db.getCollection(collName);          // 2.插入操作          coll.insert(dbs);      }        /**       * 为集合批量插入数据       *        * @param dbses       * @param collName       */      public void insertBatch(List<DBObject> dbses, String collName) {          DBCollection coll = db.getCollection(collName);          coll.insert(dbses);      }        /**       * 根据id删除数据       *        * @param id       * @param collName       * @return 返回影响的数据条数       */      public int deleteById(String id, String collName) {          DBCollection coll = db.getCollection(collName);          DBObject dbs = new BasicDBObject("_id", new ObjectId(id));          int count = coll.remove(dbs).getN();          return count;      }        /**       * 根据条件删除数据       *        * @param id       * @param collName       * @return 返回影响的数据条数       */      public int deleteByDbs(DBObject dbs, String collName) {          DBCollection coll = db.getCollection(collName);          int count = coll.remove(dbs).getN();          return count;      }        /**       * 更新数据       *        * @param find       *            查询器       * @param update       *            更新器       * @param upsert       *            更新或插入       * @param multi       *            是否批量更新       * @param collName       *            集合名称       * @return 返回影响的数据条数       */      public int update(DBObject find, DBObject update, boolean upsert,              boolean multi, String collName) {          DBCollection coll = db.getCollection(collName);          int count = coll.update(find, update, upsert, multi).getN();          return count;      }        /**       * 查询(分页)       * @param ref       * @param keys       * @param start       * @param limit       * @return       */      public DBCursor find(DBObject ref, DBObject keys, int start, int limit,              String collName) {          DBCursor cur = find(ref, keys, collName);          return cur.limit(limit).skip(start);      }        /**       * 查询 (不分页)       * @param ref       * @param keys       * @param start       * @param limit       * @param collName       * @return       */      public DBCursor find(DBObject ref, DBObject keys, String collName) {          DBCollection coll = db.getCollection(collName);          DBCursor cur = coll.find(ref, keys);          return cur;      }  }

注意:connection.close();最后别忘记调用,另外 做过java的同学都知道连接池 以及释放回收链接问题。mongodb自动内部实现了连接池。不需要再考虑该问题,也可以自行实现设置。