本文實例講述了Java單例模式下的MongoDB數(shù)據(jù)庫操作工具類。分享給大家供大家參考,具體如下:
我經常對MongoDB進行一些基礎操作,將這些常用操作合并到一個工具類中,方便自己開發(fā)使用。
沒用Spring Data、Morphia等框架是為了減少學習、維護成本,另外自己直接JDBC方式的話可以更靈活,為自己以后的積累留一個腳印。
JAVA驅動版本:
1
2
3
4
5
6
|
<!-- MongoDB驅動 --> < dependency > < groupId >org.mongodb</ groupId > < artifactId >mongo-java-driver</ artifactId > < version >3.0.2</ version > </ dependency > |
工具類代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
package utils; import java.util.ArrayList; import java.util.List; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions.Builder; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; import com.mongodb.client.model.Filters; import com.mongodb.client.result.DeleteResult; /** * MongoDB工具類 Mongo實例代表了一個數(shù)據(jù)庫連接池,即使在多線程的環(huán)境中,一個Mongo實例對我們來說已經足夠了<br> * 注意Mongo已經實現(xiàn)了連接池,并且是線程安全的。 <br> * 設計為單例模式, 因 MongoDB的Java驅動是線程安全的,對于一般的應用,只要一個Mongo實例即可,<br> * Mongo有個內置的連接池(默認為10個) 對于有大量寫和讀的環(huán)境中,為了確保在一個Session中使用同一個DB時,<br> * DB和DBCollection是絕對線程安全的<br> * * @author zhoulingfei * @date 2015-5-29 上午11:49:49 * @version 0.0.0 * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved. */ public enum MongoDBUtil { /** * 定義一個枚舉的元素,它代表此類的一個實例 */ instance; private MongoClient mongoClient; static { System.out.println( "===============MongoDBUtil初始化========================" ); CompositeConfiguration config = new CompositeConfiguration(); try { config.addConfiguration( new PropertiesConfiguration( "mongodb.properties" )); } catch (ConfigurationException e) { e.printStackTrace(); } // 從配置文件中獲取屬性值 String ip = config.getString( "host" ); int port = config.getInt( "port" ); instance.mongoClient = new MongoClient(ip, port); // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018)); // instance.mongoClient = new MongoClient(listHost); // 大部分用戶使用mongodb都在安全內網下,但如果將mongodb設為安全驗證模式,就需要在客戶端提供用戶名和密碼: // boolean auth = db.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); // options.autoConnectRetry(true);// 自動重連true // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time options.connectionsPerHost( 300 ); // 連接池設置為300個連接,默認為100 options.connectTimeout( 15000 ); // 連接超時,推薦>3000毫秒 options.maxWaitTime( 5000 ); // options.socketTimeout( 0 ); // 套接字超時時間,0無限制 options.threadsAllowedToBlockForConnectionMultiplier( 5000 ); // 線程隊列數(shù),如果連接線程排滿了隊列就會拋出“Out of semaphores to get db”錯誤。 options.writeConcern(WriteConcern.SAFE); // options.build(); } // ------------------------------------共用方法--------------------------------------------------- /** * 獲取DB實例 - 指定DB * * @param dbName * @return */ public MongoDatabase getDB(String dbName) { if (dbName != null && ! "" .equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null ; } /** * 獲取collection對象 - 指定Collection * * @param collName * @return */ public MongoCollection<Document> getCollection(String dbName, String collName) { if ( null == collName || "" .equals(collName)) { return null ; } if ( null == dbName || "" .equals(dbName)) { return null ; } MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName); return collection; } /** * 查詢DB下的所有表名 */ public List<String> getAllCollections(String dbName) { MongoIterable<String> colls = getDB(dbName).listCollectionNames(); List<String> _list = new ArrayList<String>(); for (String s : colls) { _list.add(s); } return _list; } /** * 獲取所有數(shù)據(jù)庫名稱列表 * * @return */ public MongoIterable<String> getAllDBNames() { MongoIterable<String> s = mongoClient.listDatabaseNames(); return s; } /** * 刪除一個數(shù)據(jù)庫 */ public void dropDB(String dbName) { getDB(dbName).drop(); } /** * 查找對象 - 根據(jù)主鍵_id * * @param collection * @param id * @return */ public Document findById(MongoCollection<Document> coll, String id) { ObjectId _idobj = null ; try { _idobj = new ObjectId(id); } catch (Exception e) { return null ; } Document myDoc = coll.find(Filters.eq( "_id" , _idobj)).first(); return myDoc; } /** 統(tǒng)計數(shù) */ public int getCount(MongoCollection<Document> coll) { int count = ( int ) coll.count(); return count; } /** 條件查詢 */ public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) { return coll.find(filter).iterator(); } /** 分頁查詢 */ public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) { Bson orderBy = new BasicDBObject( "_id" , 1 ); return coll.find(filter).sort(orderBy).skip((pageNo - 1 ) * pageSize).limit(pageSize).iterator(); } /** * 通過ID刪除 * * @param coll * @param id * @return */ public int deleteById(MongoCollection<Document> coll, String id) { int count = 0 ; ObjectId _id = null ; try { _id = new ObjectId(id); } catch (Exception e) { return 0 ; } Bson filter = Filters.eq( "_id" , _id); DeleteResult deleteResult = coll.deleteOne(filter); count = ( int ) deleteResult.getDeletedCount(); return count; } /** * FIXME * * @param coll * @param id * @param newdoc * @return */ public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) { ObjectId _idobj = null ; try { _idobj = new ObjectId(id); } catch (Exception e) { return null ; } Bson filter = Filters.eq( "_id" , _idobj); // coll.replaceOne(filter, newdoc); // 完全替代 coll.updateOne(filter, new Document( "$set" , newdoc)); return newdoc; } public void dropCollection(String dbName, String collName) { getDB(dbName).getCollection(collName).drop(); } /** * 關閉Mongodb */ public void close() { if (mongoClient != null ) { mongoClient.close(); mongoClient = null ; } } /** * 測試入口 * * @param args */ public static void main(String[] args) { String dbName = "GC_MAP_DISPLAY_DB" ; String collName = "COMMUNITY_BJ" ; MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName); // 插入多條 // for (int i = 1; i <= 4; i++) { // Document doc = new Document(); // doc.put("name", "zhoulf"); // doc.put("school", "NEFU" + i); // Document interests = new Document(); // interests.put("game", "game" + i); // interests.put("ball", "ball" + i); // doc.put("interests", interests); // coll.insertOne(doc); // } // // 根據(jù)ID查詢 // String id = "556925f34711371df0ddfd4b"; // Document doc = MongoDBUtil2.instance.findById(coll, id); // System.out.println(doc); // 查詢多個 // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator(); // while (cursor1.hasNext()) { // org.bson.Document _doc = (Document) cursor1.next(); // System.out.println(_doc.toString()); // } // cursor1.close(); // 查詢多個 // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator(); // 刪除數(shù)據(jù)庫 // MongoDBUtil2.instance.dropDB("testdb"); // 刪除表 // MongoDBUtil2.instance.dropCollection(dbName, collName); // 修改數(shù)據(jù) // String id = "556949504711371c60601b5a"; // Document newdoc = new Document(); // newdoc.put("name", "時候"); // MongoDBUtil.instance.updateById(coll, id, newdoc); // 統(tǒng)計表 // System.out.println(MongoDBUtil.instance.getCount(coll)); // 查詢所有 Bson filter = Filters.eq( "count" , 0 ); MongoDBUtil.instance.find(coll, filter); } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/zhoulf/p/4571647.html