首页 > 数据库 > MongoDB > 正文

Java操作MongoDB数据库示例分享

2020-03-14 13:25:02
字体:大 中 小
来源:转载
供稿:网友

MongoDB是一个文档型数据库,是NOSQL家族中最重要的成员之一,以下代码封装了MongoDB的基本操作。具体都在备注当中,要仔细看哦

MongoDB是一个文档型数据库,是NOSQL家族中最重要的成员之一,以下代码封装了MongoDB的基本操作。

MongoDBConfig.java

 

 
  1. package com.posoftframework.mongodb; 
  2. import java.io.File; 
  3. import java.io.FileInputStream; 
  4. import java.io.IOException; 
  5. import java.util.Enumeration; 
  6. import java.util.HashMap; 
  7. import java.util.Hashtable; 
  8. import java.util.List; 
  9. import java.util.Map; 
  10. import java.util.Properties; 
  11. import com.mongodb.DB; 
  12. import com.mongodb.Mongo; 
  13. /** 
  14. * MongoDB配置类 
  15. *  
  16. * @author yongtree 
  17. * @date 2010-7-7 下午07:45:08 
  18. * @version 1.0 
  19. */ 
  20. public class MongoDBConfig { 
  21. private static Mongo mongo; 
  22. private static DB db; 
  23. private static final String MONGO_DB_ADDRESS = "localhost"; 
  24. private static final int MONGO_DB_PORT = 27017; 
  25. private static final String MONGO_DB_USERNAME = "root"; 
  26. private static final String MONGO_DB_PASSWORD = "root"; 
  27. private static final String MONGO_DB_DBNAME = "mongodb"; 
  28. private static final String MONGO_DB_RESOURCE_FILE = "mongodb.cfg.properties"; 
  29. /** 
  30. * Mongo数据库参数 
  31. */ 
  32. private static Map<String, String> cfgMap = new HashMap<String, String>(); 
  33. private static Hashtable<String, DB> mongoDBs = new Hashtable<String, DB>(); 
  34. /** 
  35. * 初始化Mongo的数据库 
  36. */ 
  37. static { 
  38. init(); 
  39. } 
  40. public static File getConfigFile() { 
  41. String path = MongoDBConfig.class.getResource("/").getPath(); 
  42. String fileName = path + MONGO_DB_RESOURCE_FILE; 
  43. File file = new File(fileName); 
  44. if (file.exists()) { 
  45. return file; 
  46. } 
  47. return null; 
  48. } 
  49. @SuppressWarnings("unchecked") 
  50. private static void initCfgMap() { 
  51. File file = getConfigFile(); 
  52. if (file != null) { 
  53. Properties p = new Properties(); 
  54. try { 
  55. p.load(new FileInputStream(file)); 
  56. for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) { 
  57. String key = (String) enu.nextElement(); 
  58. String value = (String) p.getProperty(key); 
  59. cfgMap.put(key, value); 
  60. } 
  61. } catch (IOException e) { 
  62. System.out.println("记载Mongo配置文件失败!"); 
  63. e.printStackTrace(); 
  64. } 
  65. } else { 
  66. cfgMap.put("mongo.db.address", MONGO_DB_ADDRESS); 
  67. cfgMap.put("mongo.db.port", String.valueOf(MONGO_DB_PORT)); 
  68. cfgMap.put("mongo.db.username", MONGO_DB_USERNAME); 
  69. cfgMap.put("mongo.db.password", MONGO_DB_PASSWORD); 
  70. cfgMap.put("mongo.db.dbname", MONGO_DB_DBNAME); 
  71. } 
  72. } 
  73. /** 
  74. * 初始化Mongo数据库 
  75. */ 
  76. private static void init() { 
  77. initCfgMap(); 
  78. try { 
  79. String address = cfgMap.get("mongo.db.address"); 
  80. int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString()); 
  81. String dbName = cfgMap.get("mongo.db.dbname"); 
  82. String username = cfgMap.get("mongo.db.username"); 
  83. String password = cfgMap.get("mongo.db.password"); 
  84. mongo = new Mongo(address, port); 
  85. if (dbName != null && !"".equals(dbName)) { 
  86. db = mongo.getDB(dbName); 
  87. if (username != null && !"".equals(username)) { 
  88. db.addUser(username, password.toCharArray()); 
  89. } 
  90. mongoDBs.put(dbName, db); 
  91. } 
  92. } catch (IOException e) { 
  93. e.printStackTrace(); 
  94. } 
  95. } 
  96. /** 
  97. * 得到Mongo的实例 
  98. *  
  99. * @return 
  100. */ 
  101. public static Mongo getMongo() { 
  102. return mongo; 
  103. } 
  104. /** 
  105. * 得到Mongo的图片数据库 
  106. *  
  107. * @return 
  108. */ 
  109. public static DB getDB() { 
  110. return db; 
  111. } 
  112. public static List<String> getDBNames() { 
  113. return mongo.getDatabaseNames(); 
  114. } 
  115. /** 
  116. * 根据数据库名称,得到数据库<br/> 
  117. * 如果不存在,则创建一个该名称的数据库,并设置用户名和密码为配置文件中的参数值</br> 
  118. *  
  119. * @param dbName 
  120. * @return 
  121. */ 
  122. public static DB getDBByName(String dbName) { 
  123. DB db = mongo.getDB(dbName); 
  124. if (!mongoDBs.contains(db)) { 
  125. db.addUser(cfgMap.get("mongo.db.username"), cfgMap.get( 
  126. "mongo.db.password").toCharArray()); 
  127. mongoDBs.put(dbName, db); 
  128. } 
  129. return db; 
  130. } 
  131. } 

MongoService.java

 

 
  1. /************************* 版权声明 ********************************* 
  2. * * 
  3. * 版权所有:百洋软件 * 
  4. * Copyright (c) 2010 by www.po-soft.com * 
  5. * * 
  6. ************************* 变更记录 ********************************* 
  7. * 
  8. * 创建者:yongtree 创建日期: 2010-7-7 
  9. * 备注: 
  10. *  
  11. * 修改者: 修改日期: 
  12. * 备注: 
  13. *  
  14. */ 
  15. package com.posoftframework.mongodb; 
  16. import java.util.List; 
  17. import java.util.Map; 
  18. import com.mongodb.DB; 
  19. import com.mongodb.DBCollection; 
  20. import com.mongodb.DBObject; 
  21. /** 
  22. * 操作MongoDB的DAO接口 
  23. *  
  24. * @author yongtree 
  25. * @date 2010-7-7 下午04:44:43 
  26. * @version 1.0 
  27. */ 
  28. public interface MongoService { 
  29. public abstract DBCollection getCollection(); 
  30. /** 
  31. * 根据数据集合的Map,插入数据 map的key对应数据库中的DBCollection的key值 
  32. *  
  33. * @param obj 
  34. */ 
  35. public abstract DBObject insert(DBObject obj); 
  36. /** 
  37. * 根据List<Map<String,Object>>结构的数据集合,插入数据 
  38. *  
  39. * @param list 
  40. */ 
  41. public abstract void insertBatch(List<DBObject> list); 
  42. /** 
  43. * 按照条件参数集合map,删除数据 
  44. *  
  45. * @param map 
  46. */ 
  47. public abstract void delete(DBObject obj); 
  48. /** 
  49. * 按照多种条件的并集,批量删除数据 
  50. *  
  51. * @param list 
  52. */ 
  53. public abstract void deleteBatch(List<DBObject> list); 
  54. /** 
  55. * 得到Collection()总的记录数 
  56. *  
  57. * @return 
  58. */ 
  59. public abstract long getCollectionCount(); 
  60. public abstract long getCount(DBObject query); 
  61. public abstract List<DBObject> find(DBObject query); 
  62. public abstract List<DBObject> find(DBObject query,DBObject sort); 
  63. public abstract List<DBObject> find(DBObject query,DBObject sort,int start,int limit); 
  64. /** 
  65. * 根据whereFields参数,更新setFields值 
  66. *  
  67. * @param setFields 
  68. * @param whereFields 
  69. */ 
  70. public abstract void update(DBObject setFields, 
  71. DBObject whereFields); 
  72. public abstract List<DBObject> findAll(); 
  73. /** 
  74. * 根据ID找到唯一数据 有1个id字段标记 
  75. *  
  76. * @param id 
  77. * @return 
  78. */ 
  79. public abstract DBObject getById(String id); 
  80. /** 
  81. * 获取所有数据库名称 
  82. *  
  83. * @return 
  84. */ 
  85. public List<String> getAllDBNames(); 
  86. public abstract String getDbName(); 
  87. public abstract void setDbName(String dbName); 
  88. public abstract DB getDb(); 
  89. public abstract String getCollName(); 
  90. public abstract void setCollName(String collName); 
  91. } 

MongoServiceImpl.java

 

  1. /************************* 版权声明 ********************************* 
  2. * * 
  3. * 版权所有:百洋软件 * 
  4. * Copyright (c) 2010 by www.po-soft.com * 
  5. * * 
  6. ************************* 变更记录 ********************************* 
  7. * 
  8. * 创建者:yongtree 创建日期: 2010-7-7 
  9. * 备注: 
  10. *  
  11. * 修改者: 修改日期: 
  12. * 备注: 
  13. *  
  14. */ 
  15. package com.posoftframework.mongodb; 
  16. import java.util.ArrayList; 
  17. import java.util.List; 
  18. import java.util.Map; 
  19. import org.bson.types.ObjectId; 
  20. import com.mongodb.BasicDBObject; 
  21. import com.mongodb.DB; 
  22. import com.mongodb.DBCollection; 
  23. import com.mongodb.DBCursor; 
  24. import com.mongodb.DBObject; 
  25. /** 
  26. *  
  27. * @author yongtree 
  28. * @date 2010-7-7 下午07:22:15 
  29. * @version 1.0 
  30. */ 
  31. public class MongoServiceImpl implements MongoService { 
  32. private String dbName; 
  33. private String collName; 
  34. private DB db; 
  35. public MongoServiceImpl(String dbName, String collName) { 
  36. this.dbName = dbName; 
  37. this.collName = collName; 
  38. try { 
  39. db = MongoDBConfig.getDBByName(this.dbName); 
  40. } catch (Throwable e) { 
  41. e.printStackTrace(); 
  42. } 
  43. } 
  44. public MongoServiceImpl() { 
  45. getDb(); 
  46. } 
  47. public DBCollection getCollection() { 
  48. return db.getCollection(this.collName); 
  49. } 
  50. public DBObject map2Obj(Map<String, Object> map) { 
  51. DBObject obj = new BasicDBObject(); 
  52. if (map.containsKey("class") && map.get("class") instanceof Class) 
  53. map.remove("class"); 
  54. obj.putAll(map); 
  55. return obj; 
  56. } 
  57. public DBObject insert(DBObject obj) { 
  58. getCollection().insert(obj); 
  59. return obj; 
  60. } 
  61. public void insertBatch(List<DBObject> list) { 
  62. if (list == null || list.isEmpty()) { 
  63. return; 
  64. } 
  65. List<DBObject> listDB = new ArrayList<DBObject>(); 
  66. for (int i = 0; i < list.size(); i++) { 
  67. listDB.add(list.get(i)); 
  68. } 
  69. getCollection().insert(listDB); 
  70. } 
  71. public void delete(DBObject obj) { 
  72. getCollection().remove(obj); 
  73. } 
  74. public void deleteBatch(List<DBObject> list) { 
  75. if (list == null || list.isEmpty()) { 
  76. return; 
  77. } 
  78. for (int i = 0; i < list.size(); i++) { 
  79. getCollection().remove(list.get(i)); 
  80. } 
  81. } 
  82. public long getCollectionCount() { 
  83. return getCollection().getCount(); 
  84. } 
  85. public long getCount(DBObject obj) { 
  86. if (obj != null) 
  87. return getCollection().getCount(obj); 
  88. return getCollectionCount(); 
  89. } 
  90. public List<DBObject> find(DBObject obj) { 
  91. DBCursor cur = getCollection().find(obj); 
  92. return DBCursor2list(cur); 
  93. } 
  94. @Override 
  95. public List<DBObject> find(DBObject query, DBObject sort) { 
  96. DBCursor cur; 
  97. if (query != null) { 
  98. cur = getCollection().find(query); 
  99. } else { 
  100. cur = getCollection().find(); 
  101. } 
  102. if (sort != null) { 
  103. cur.sort(sort); 
  104. } 
  105. return DBCursor2list(cur); 
  106. } 
  107. @Override 
  108. public List<DBObject> find(DBObject query, DBObject sort, int start, 
  109. int limit) { 
  110. DBCursor cur; 
  111. if (query != null) { 
  112. cur = getCollection().find(query); 
  113. } else { 
  114. cur = getCollection().find(); 
  115. } 
  116. if (sort != null) { 
  117. cur.sort(sort); 
  118. } 
  119. if (start == 0) { 
  120. cur.batchSize(limit); 
  121. } else { 
  122. cur.skip(start).limit(limit); 
  123. } 
  124. return DBCursor2list(cur); 
  125. } 
  126. private List<DBObject> DBCursor2list(DBCursor cur) { 
  127. List<DBObject> list = new ArrayList<DBObject>(); 
  128. if (cur != null) { 
  129. list = cur.toArray(); 
  130. } 
  131. return list; 
  132. } 
  133. public void update(DBObject setFields, DBObject whereFields) { 
  134. getCollection().updateMulti(setFields, whereFields); 
  135. } 
  136. public List<DBObject> findAll() { 
  137. DBCursor cur = getCollection().find(); 
  138. List<DBObject> list = new ArrayList<DBObject>(); 
  139. if (cur != null) { 
  140. list = cur.toArray(); 
  141. } 
  142. return list; 
  143. } 
  144. public DBObject getById(String id) { 
  145. DBObject obj = new BasicDBObject(); 
  146. obj.put("_id", new ObjectId(id)); 
  147. DBObject result = getCollection().findOne(obj); 
  148. return result; 
  149. } 
  150. public String getDbName() { 
  151. return dbName; 
  152. } 
  153. public void setDbName(String dbName) { 
  154. this.dbName = dbName; 
  155. this.db = MongoDBConfig.getDBByName(this.dbName); 
  156. } 
  157. public String getCollName() { 
  158. return collName; 
  159. } 
  160. public void setCollName(String collName) { 
  161. this.collName = collName; 
  162. } 
  163. public DB getDb() { 
  164. if (this.db == null) { 
  165. if (this.dbName == null) { 
  166. this.db = MongoDBConfig.getDB(); 
  167. } else { 
  168. this.db = MongoDBConfig.getDBByName(this.dbName); 
  169. } 
  170. } 
  171. return this.db; 
  172. } 
  173. public List<String> getAllDBNames() { 
  174. return MongoDBConfig.getDBNames(); 
  175. } 
  176. } 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表