Java操作MongoDB數據庫示例分享



MongoDBConfig.java

?

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

120

121

122

123

124

125

126

127

128

129

130

131

package com.posoftframework.mongodb;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.Hashtable;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import com.mongodb.DB;

import com.mongodb.Mongo;

/**

 * MongoDB配置類

 *

 *

 * @version 1.0

 */

public class MongoDBConfig {

  private static Mongo mongo;

  private static DB db;

  private static final String MONGO_DB_ADDRESS = "localhost";

  private static final int MONGO_DB_PORT = 27017;

  private static final String MONGO_DB_USERNAME = "root";

  private static final String MONGO_DB_PASSWORD = "root";

  private static final String MONGO_DB_DBNAME = "mongodb";

  private static final String MONGO_DB_RESOURCE_FILE = "mongodb.cfg.properties";

  /**

   * Mongo數據庫參數

   */

  private static Map<String, String> cfgMap = new HashMap<String, String>();

  private static Hashtable<String, DB> mongoDBs = new Hashtable<String, DB>();

  /**

   * 初始化Mongo的數據庫

   */

  static {

    init();

  }

  public static File getConfigFile() {

    String path = MongoDBConfig.class.getResource("/").getPath();

    String fileName = path + MONGO_DB_RESOURCE_FILE;

    File file = new File(fileName);

    if (file.exists()) {

      return file;

    }

    return null;

  }

  @SuppressWarnings("unchecked")

  private static void initCfgMap() {

    File file = getConfigFile();

    if (file != null) {

      Properties p = new Properties();

      try {

        p.load(new FileInputStream(file));

        for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) {

          String key = (String) enu.nextElement();

          String value = (String) p.getProperty(key);

          cfgMap.put(key, value);

        }

      } catch (IOException e) {

        System.out.println("記載Mongo配置文件失敗!");

        e.printStackTrace();

      }

    } else {

      cfgMap.put("mongo.db.address", MONGO_DB_ADDRESS);

      cfgMap.put("mongo.db.port", String.valueOf(MONGO_DB_PORT));

      cfgMap.put("mongo.db.username", MONGO_DB_USERNAME);

      cfgMap.put("mongo.db.password", MONGO_DB_PASSWORD);

      cfgMap.put("mongo.db.dbname", MONGO_DB_DBNAME);

    }

  }

  /**

   * 初始化Mongo數據庫

   */

  private static void init() {

    initCfgMap();

    try {

      String address = cfgMap.get("mongo.db.address");

      int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString());

      String dbName = cfgMap.get("mongo.db.dbname");

      String username = cfgMap.get("mongo.db.username");

      String password = cfgMap.get("mongo.db.password");

      mongo = new Mongo(address, port);

      if (dbName != null && !"".equals(dbName)) {

        db = mongo.getDB(dbName);

        if (username != null && !"".equals(username)) {

          db.addUser(username, password.toCharArray());

        }

        mongoDBs.put(dbName, db);

      }

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

  /**

   * 得到Mongo的實例

   *

   * @return

   */

  public static Mongo getMongo() {

    return mongo;

  }

  /**

   * 得到Mongo的圖片數據庫

   *

   * @return

   */

  public static DB getDB() {

    return db;

  }

  public static List<String> getDBNames() {

    return mongo.getDatabaseNames();

  }

  /**

   * 根據數據庫名稱,得到數據庫<br/>

   * 如果不存在,則創建一個該名稱的數據庫,並設置用戶名和密碼爲配置文件中的參數值</br>

   *

   * @param dbName

   * @return

   */

  public static DB getDBByName(String dbName) {

    DB db = mongo.getDB(dbName);

    if (!mongoDBs.contains(db)) {

      db.addUser(cfgMap.get("mongo.db.username"), cfgMap.get(

          "mongo.db.password").toCharArray());

      mongoDBs.put(dbName, db);

    }

    return db;

  }

}

MongoService.java

?

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

 ************************* 變更記錄 *********************************

 *

 * * 備註:

 *

 * 修改者:    修改日期:

 * 備註:

 *

 */

package com.posoftframework.mongodb;

import java.util.List;

import java.util.Map;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBObject;

/**

 * 操作MongoDBDAO接口

 *

 *

 * @date 2010-7-7 下午04:44:43

 * @version 1.0

 */

public interface MongoService {

  public abstract DBCollection getCollection();

  /**

   * 根據數據集合的Map,插入數據 mapkey對應數據庫中的DBCollectionkey

   *

   * @param obj

   */

  public abstract DBObject insert(DBObject obj);

  /**

   * 根據List<Map<String,Object>>結構的數據集合,插入數據

   *

   * @param list

   */

  public abstract void insertBatch(List<DBObject> list);

  /**

   * 按照條件參數集合map,刪除數據

   *

   * @param map

   */

  public abstract void delete(DBObject obj);

  /**

   * 按照多種條件的並集,批量刪除數據

   *

   * @param list

   */

  public abstract void deleteBatch(List<DBObject> list);

  /**

   * 得到Collection()總的記錄數

   *

   * @return

   */

  public abstract long getCollectionCount();

  public abstract long getCount(DBObject query);

  public abstract List<DBObject> find(DBObject query);

  public abstract List<DBObject> find(DBObject query,DBObject sort);

  public abstract List<DBObject> find(DBObject query,DBObject sort,int start,int limit);

  /**

   * 根據whereFields參數,更新setFields

   *

   * @param setFields

   * @param whereFields

   */

  public abstract void update(DBObject setFields,

      DBObject whereFields);

  public abstract List<DBObject> findAll();

  /**

   * 根據ID找到唯一數據 1id字段標記

   *

   * @param id

   * @return

   */

  public abstract DBObject getById(String id);

  /**

   * 獲取所有數據庫名稱

   *

   * @return

   */

  public List<String> getAllDBNames();

  public abstract String getDbName();

  public abstract void setDbName(String dbName);

  public abstract DB getDb();

  public abstract String getCollName();

  public abstract void setCollName(String collName);

}

MongoServiceImpl.java

?

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

 ************************* 變更記錄 *********************************

 *

 *

 * 備註:

 *

 * 修改者:    修改日期:

 * 備註:

 *

 */

package com.posoftframework.mongodb;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

/**

 *

 * @author yongtree

 * @date 2010-7-7 下午07:22:15

 * @version 1.0

 */

public class MongoServiceImpl implements MongoService {

  private String dbName;

  private String collName;

  private DB db;

  public MongoServiceImpl(String dbName, String collName) {

    this.dbName = dbName;

    this.collName = collName;

    try {

      db = MongoDBConfig.getDBByName(this.dbName);

    } catch (Throwable e) {

      e.printStackTrace();

    }

  }

  public MongoServiceImpl() {

    getDb();

  }

  public DBCollection getCollection() {

    return db.getCollection(this.collName);

  }

  public DBObject map2Obj(Map<String, Object> map) {

    DBObject obj = new BasicDBObject();

    if (map.containsKey("class") && map.get("class") instanceof Class)

      map.remove("class");

    obj.putAll(map);

    return obj;

  }

  public DBObject insert(DBObject obj) {

    getCollection().insert(obj);

    return obj;

  }

  public void insertBatch(List<DBObject> list) {

    if (list == null || list.isEmpty()) {

      return;

    }

    List<DBObject> listDB = new ArrayList<DBObject>();

    for (int i = 0; i < list.size(); i++) {

      listDB.add(list.get(i));

    }

    getCollection().insert(listDB);

  }

  public void delete(DBObject obj) {

    getCollection().remove(obj);

  }

  public void deleteBatch(List<DBObject> list) {

    if (list == null || list.isEmpty()) {

      return;

    }

    for (int i = 0; i < list.size(); i++) {

      getCollection().remove(list.get(i));

    }

  }

  public long getCollectionCount() {

    return getCollection().getCount();

  }

  public long getCount(DBObject obj) {

    if (obj != null)

      return getCollection().getCount(obj);

    return getCollectionCount();

  }

  public List<DBObject> find(DBObject obj) {

    DBCursor cur = getCollection().find(obj);

    return DBCursor2list(cur);

  }

  @Override

  public List<DBObject> find(DBObject query, DBObject sort) {

    DBCursor cur;

    if (query != null) {

      cur = getCollection().find(query);

    } else {

      cur = getCollection().find();

    }

    if (sort != null) {

      cur.sort(sort);

    }

    return DBCursor2list(cur);

  }

  @Override

  public List<DBObject> find(DBObject query, DBObject sort, int start,

      int limit) {

    DBCursor cur;

    if (query != null) {

      cur = getCollection().find(query);

    } else {

      cur = getCollection().find();

    }

    if (sort != null) {

      cur.sort(sort);

    }

    if (start == 0) {

      cur.batchSize(limit);

    } else {

      cur.skip(start).limit(limit);

    }

    return DBCursor2list(cur);

  }

  private List<DBObject> DBCursor2list(DBCursor cur) {

    List<DBObject> list = new ArrayList<DBObject>();

    if (cur != null) {

      list = cur.toArray();

    }

    return list;

  }

  public void update(DBObject setFields, DBObject whereFields) {

    getCollection().updateMulti(setFields, whereFields);

  }

  public List<DBObject> findAll() {

    DBCursor cur = getCollection().find();

    List<DBObject> list = new ArrayList<DBObject>();

    if (cur != null) {

      list = cur.toArray();

    }

    return list;

  }

  public DBObject getById(String id) {

    DBObject obj = new BasicDBObject();

    obj.put("_id", new ObjectId(id));

    DBObject result = getCollection().findOne(obj);

    return result;

  }

  public String getDbName() {

    return dbName;

  }

  public void setDbName(String dbName) {

    this.dbName = dbName;

    this.db = MongoDBConfig.getDBByName(this.dbName);

  }

  public String getCollName() {

    return collName;

  }

  public void setCollName(String collName) {

    this.collName = collName;

  }

  public DB getDb() {

    if (this.db == null) {

      if (this.dbName == null) {

        this.db = MongoDBConfig.getDB();

      } else {

        this.db = MongoDBConfig.getDBByName(this.dbName);

      }

    }

    return this.db;

  }

  public List<String> getAllDBNames() {

    return MongoDBConfig.getDBNames();

  }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章