/mongodb/src/main/java/org/grain/mongo/MongodbManager.java

https://github.com/dianbaer/grain · Java · 314 lines · 192 code · 19 blank · 103 comment · 41 complexity · 8bca5747a95aab32115b2e649f27a2f3 MD5 · raw file

  1. package org.grain.mongo;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import org.bson.Document;
  6. import org.bson.conversions.Bson;
  7. import org.grain.log.ILog;
  8. import com.google.gson.Gson;
  9. import com.mongodb.MongoClient;
  10. import com.mongodb.MongoCommandException;
  11. import com.mongodb.MongoCredential;
  12. import com.mongodb.ServerAddress;
  13. import com.mongodb.client.MongoCollection;
  14. import com.mongodb.client.MongoCursor;
  15. import com.mongodb.client.MongoDatabase;
  16. import com.mongodb.client.model.Filters;
  17. import com.mongodb.client.result.DeleteResult;
  18. import com.mongodb.client.result.UpdateResult;
  19. public class MongodbManager {
  20. public static MongoClient mongoClient;
  21. public static MongoDatabase mongoDatabase;
  22. public static String URL;
  23. public static int PORT;
  24. public static String USERNAME;
  25. public static String PASSWORD;
  26. public static String DBNAME;
  27. public static ILog log;
  28. /**
  29. * 初始化mongodb
  30. *
  31. * @param url
  32. * 地址
  33. * @param port
  34. * 端口
  35. * @param username
  36. * 用户名
  37. * @param password
  38. * 密码
  39. * @param dbName
  40. * 数据库名
  41. * @param log
  42. * 日志可以为null
  43. */
  44. public static void init(String url, int port, String username, String password, String dbName, ILog log) {
  45. MongodbManager.URL = url;
  46. MongodbManager.PORT = port;
  47. MongodbManager.USERNAME = username;
  48. MongodbManager.PASSWORD = password;
  49. MongodbManager.DBNAME = dbName;
  50. MongodbManager.log = log;
  51. MongoCredential mongoCredential = MongoCredential.createCredential(username, dbName, password.toCharArray());
  52. mongoClient = new MongoClient(new ServerAddress(url, port), Arrays.asList(mongoCredential));
  53. mongoDatabase = mongoClient.getDatabase(MongodbManager.DBNAME);
  54. }
  55. /**
  56. * 创建表
  57. *
  58. * @param name
  59. * 表名
  60. * @return
  61. */
  62. public static boolean createCollection(String name) {
  63. try {
  64. mongoDatabase.createCollection(name);
  65. return true;
  66. } catch (MongoCommandException e) {
  67. if (e.getCode() != 48) {
  68. if (log != null) {
  69. log.error("创建集合失败", e);
  70. }
  71. } else {
  72. if (log != null) {
  73. log.warn("创建集合失败,已存在此集合");
  74. }
  75. }
  76. return false;
  77. } catch (Exception e) {
  78. if (log != null) {
  79. log.error("创建集合失败", e);
  80. }
  81. return false;
  82. }
  83. }
  84. /**
  85. * 获取表的链接
  86. *
  87. * @param collectionName
  88. * 表名
  89. * @return
  90. */
  91. public static MongoCollection<Document> getCollection(String collectionName) {
  92. MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
  93. return collection;
  94. }
  95. /**
  96. * 对象转mongodb格式
  97. *
  98. * @param obj
  99. * @return
  100. */
  101. public static Document objectToDocument(Object obj) {
  102. Gson gson = new Gson();
  103. String objStr = gson.toJson(obj);
  104. Document document = Document.parse(objStr);
  105. return document;
  106. }
  107. /**
  108. * mongodb转对象格式
  109. *
  110. * @param document
  111. * @param clazz
  112. * @return
  113. */
  114. public static <T> T documentToObject(Document document, Class<T> clazz) {
  115. Gson gson = new Gson();
  116. String objStr = document.toJson();
  117. T obj = gson.fromJson(objStr, clazz);
  118. return obj;
  119. }
  120. /**
  121. * 插入一条记录
  122. *
  123. * @param collectionName
  124. * 表名
  125. * @param mongoObj
  126. * 记录
  127. * @return
  128. */
  129. public static boolean insertOne(String collectionName, MongoObj mongoObj) {
  130. MongoCollection<Document> collection = getCollection(collectionName);
  131. try {
  132. Document document = objectToDocument(mongoObj);
  133. collection.insertOne(document);
  134. return true;
  135. } catch (Exception e) {
  136. if (log != null) {
  137. log.error("插入document失败", e);
  138. }
  139. return false;
  140. }
  141. }
  142. /**
  143. * 插入list
  144. *
  145. * @param collectionName
  146. * 表名
  147. * @param list
  148. * list
  149. * @return
  150. */
  151. public static boolean insertMany(String collectionName, List<MongoObj> list) {
  152. MongoCollection<Document> collection = getCollection(collectionName);
  153. try {
  154. ArrayList<Document> documentList = new ArrayList<>();
  155. for (int i = 0; i < list.size(); i++) {
  156. MongoObj mongoObj = list.get(i);
  157. Document document = objectToDocument(mongoObj);
  158. documentList.add(document);
  159. }
  160. collection.insertMany(documentList);
  161. return true;
  162. } catch (Exception e) {
  163. if (log != null) {
  164. log.error("插入documentList失败", e);
  165. }
  166. return false;
  167. }
  168. }
  169. /**
  170. * 查询列表
  171. *
  172. * @param collectionName
  173. * 表名
  174. * @param filter
  175. * 过滤条件
  176. * @param clazz
  177. * 类名
  178. * @param start
  179. * 开始条数
  180. * @param pageSize
  181. * 多少条
  182. * @return
  183. */
  184. public static <T> List<T> find(String collectionName, Bson filter, Class<T> clazz, int start, int pageSize) {
  185. MongoCollection<Document> collection = getCollection(collectionName);
  186. try {
  187. MongoCursor<Document> iterator = null;
  188. if (pageSize == 0) {
  189. if (filter == null) {
  190. iterator = collection.find().iterator();
  191. } else {
  192. iterator = collection.find(filter).iterator();
  193. }
  194. } else {
  195. if (filter == null) {
  196. iterator = collection.find().skip(start).limit(pageSize).iterator();
  197. } else {
  198. iterator = collection.find(filter).skip(start).limit(pageSize).iterator();
  199. }
  200. }
  201. ArrayList<T> list = new ArrayList<>();
  202. while (iterator.hasNext()) {
  203. Document document = iterator.next();
  204. T obj = documentToObject(document, clazz);
  205. MongoObj mongoObj = (MongoObj) obj;
  206. mongoObj.setDocument(document);
  207. list.add(obj);
  208. }
  209. return list;
  210. } catch (Exception e) {
  211. if (log != null) {
  212. log.error("查询documentList失败", e);
  213. }
  214. return null;
  215. }
  216. }
  217. /**
  218. * 删除记录
  219. *
  220. * @param collectionName
  221. * 表名
  222. * @param mongoObj
  223. * 记录
  224. * @return
  225. */
  226. public static boolean deleteById(String collectionName, MongoObj mongoObj) {
  227. MongoCollection<Document> collection = getCollection(collectionName);
  228. try {
  229. Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
  230. DeleteResult result = collection.deleteOne(filter);
  231. if (result.getDeletedCount() == 1) {
  232. return true;
  233. } else {
  234. return false;
  235. }
  236. } catch (Exception e) {
  237. if (log != null) {
  238. log.error("删除记录失败", e);
  239. }
  240. return false;
  241. }
  242. }
  243. /**
  244. * 修改记录
  245. *
  246. * @param collectionName
  247. * 表名
  248. * @param mongoObj
  249. * 对象
  250. * @return
  251. */
  252. public static boolean updateById(String collectionName, MongoObj mongoObj) {
  253. MongoCollection<Document> collection = getCollection(collectionName);
  254. try {
  255. Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
  256. mongoObj.setDocument(null);
  257. Document document = objectToDocument(mongoObj);
  258. UpdateResult result = collection.updateOne(filter, new Document(MongoConfig.$SET, document));
  259. if (result.getMatchedCount() == 1) {
  260. return true;
  261. } else {
  262. return false;
  263. }
  264. } catch (Exception e) {
  265. if (log != null) {
  266. log.error("修改记录失败", e);
  267. }
  268. return false;
  269. }
  270. }
  271. /**
  272. * 获取个数
  273. *
  274. * @param collectionName
  275. * 表名
  276. * @param filter
  277. * 过滤
  278. * @return
  279. */
  280. public static long count(String collectionName, Bson filter) {
  281. MongoCollection<Document> collection = getCollection(collectionName);
  282. try {
  283. if (filter == null) {
  284. return collection.count();
  285. } else {
  286. return collection.count(filter);
  287. }
  288. } catch (Exception e) {
  289. if (log != null) {
  290. log.error("查询个数失败", e);
  291. }
  292. return 0;
  293. }
  294. }
  295. }