mongodb使用
mongodb使用
1. 下载 mongo-2.6.3.jar
2. 新建 java项目
3. 按Spring方式封装查询 直接上代码
Java代码
1.package com.mytest;
2.
3.import java.net.UnknownHostException;
4.
5.import com.mongodb.DB;
6.import com.mongodb.DBCollection;
7.import com.mongodb.Mongo;
8.import com.mongodb.MongoException;
9.
10./**
11. *
12. *
13. * @author lw
14. * @created 2011-6-27 下午04:26:40
15. * @version 1.0.0
16. * @date 2011-6-27 下午04:26:40
17. */
18.
19.public class DBTemplate {
20. private static String MONGODB_SERVER = "192.168.42.212";
21. private static int SERVER_PORT = 27017;
22. private static String MONGODB_DBNAME = "test";
23.
24. public final Object execute(MsgCallback action, String collection) {
25. DB db = getConn();
26. DBCollection dbColl = db.getCollection(collection);
27. Object result = action.doExecute(dbColl);
28. closeDb(db);
29. closeCollection(dbColl);
30.
31. return result;
32. }
33.
34. private DB getConn() {
35. return getConn(MONGODB_SERVER, SERVER_PORT, MONGODB_DBNAME);
36. }
37.
38. private DB getConn(String server, int port, String dbName) {
39. Mongo m = null;
40. try {
41. m = new Mongo(server, port);
42. } catch (UnknownHostException e) {
43. e.printStackTrace();
44. } catch (MongoException e) {
45. e.printStackTrace();
46. }
47. return m.getDB(dbName);
48. }
49.
50. private void closeDb(DB db) {
51. if (db != null) {
52. db = null;
53. }
54. }
55.
56. private void closeCollection(DBCollection col) {
57. if (col != null) {
58. col = null;
59. }
60. }
61.}
package com.mytest;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com