1 public class BerkeleyDB {
2
3 private static String myEnvPath = Constant.user_dir + "/db";
4
5 public static Map<String, Database> databases = new HashMap<String, Database>();
6 public static Map<Class, EntryBinding> bindings = new HashMap<Class, EntryBinding>();
7
8 // DB handles
9 private static Environment myEnv = null;
10 public final static String basedbname = "basedb";
11 public final static String operatedbname = "operatedb";
12 /**
13 * 单独存储类型信息
14 */
15 public final static String classCatalogdbname = "classCatalogdb";
16
17 /**
18 *
19 * @brief openEnv
20 * @details 打开数据库环境并获取要操作的数据库,不存在则创建
21 * @warning 其中注意事项警告
22 * @note
23 * @throws DatabaseException
24 */
25 public static void openEnv() throws DatabaseException {
26 System.out.println("opening env");
27
28 // Set up the environment.
29 EnvironmentConfig myEnvConfig = new EnvironmentConfig();
30 myEnvConfig.setAllowCreate(true);
31 // Set up the database
32
33 // Open the environment
34 myEnv = new Environment(getFile(myEnvPath), // Env home
35 myEnvConfig);
36
37 Database operateDb = myEnv.openDatabase(null, operatedbname, myDbConfig());
38 databases.put(operatedbname, operateDb);
39
40 Database baseDb = myEnv.openDatabase(null, basedbname, myDbConfig());
41 databases.put(basedbname, baseDb);
42
43 Database catalogDb = myEnv.openDatabase(null, classCatalogdbname, myDbConfig());
44 databases.put(classCatalogdbname,catalogDb);
45 // 创建catalog
46 StoredClassCatalog classCatalog = new StoredClassCatalog(catalogDb);
47 // 创建绑定对象
48 EntryBinding dataBinging = new SerialBinding(classCatalog, OperateInfo.class);
49 bindings.put(OperateInfo.class, dataBinging);
50 }
51
52 //对象绑定
53 public static EntryBinding getBinding(Database db,Class clz){
54 EntryBinding dataBinging = null;
55 if(bindings.containsKey(clz)){
56 dataBinging = bindings.get(clz);
57 }else{
58 // 创建catalog
59 StoredClassCatalog classCatalog = new StoredClassCatalog(db);
60 dataBinging = new SerialBinding(classCatalog, clz);
61 }
62 return dataBinging;
63 }
64
65 //获取数据库
66 public static Database getDb(String dbname){
67 Database db = null;
68 if(databases.containsKey(dbname)){
69 db = databases.get(dbname);
70 }else{
71 db = createDb(dbname);
72 databases.put(dbname, db);
73 }
74 return db;
75 }
76
77 // 创建数据库
78 private static Database createDb(String dbname) {
79 if (databases.containsKey(dbname)) {
80 return databases.get(dbname);
81 }
82 Database database = myEnv.openDatabase(null, dbname, myDbConfig());
83 return database;
84 }
85
86 private static DatabaseConfig myDbConfig() {
87 DatabaseConfig myDbConfig = new DatabaseConfig();
88 myDbConfig.setAllowCreate(true);
89 myDbConfig.setReadOnly(false);
90 myDbConfig.setSortedDuplicates(false);
91 return myDbConfig;
92 }
93
94 /**
95 *
96 * @brief getFile
97 * @details 获取数据库环境目录,不存在则创建
98 * @warning 其中注意事项警告
99 * @note
100 * @param path
101 * @return
102 */
103 private static File getFile(String path) {
104 File file = new File(path);
105 if (!file.exists() || !file.isDirectory()) {
106 file.mkdir();
107 }
108 System.out.println("DB file: " + file.getAbsolutePath());
109 return file;
110 }
111
112 /**
113 *
114 * @brief putData
115 * @details 存储数据
116 * @warning 其中注意事项警告
117 * @note
118 * @param dbname 数据库名,不存在则创建
119 * @param key
120 * @param value
121 * @return
122 */
123 public static boolean putString(String dbname, String key, String value) {
124 Database db = getDb(dbname);
125 OperationStatus status = null;
126 try {
127 DatabaseEntry keyEntry = new DatabaseEntry(key
128 .getBytes(Constant.default_charset));
129 DatabaseEntry valueEntry = new DatabaseEntry(value
130 .getBytes(Constant.default_charset));
131 status = db.put(null, keyEntry, valueEntry);
132 } catch (UnsupportedEncodingException e) {
133 System.out.println("putString:[key:" + key + "][value:" + value
134 + "]: " + e.toString());
135 e.printStackTrace();
136 }
137 return (status!=null&&status==OperationStatus.SUCCESS)?true:false;
138 }
139
140 /**
141 *
142 */
143 public static boolean putObject(String dbname,Class clz,String key,Object value){
144 Database db = getDb(dbname);
145 EntryBinding binding = getBinding(db, clz);
146 OperationStatus status = null;
147 try {
148 DatabaseEntry theKey = new DatabaseEntry(key
149 .getBytes(Constant.default_charset));
150 DatabaseEntry theData = new DatabaseEntry();
151 binding.objectToEntry(value, theData);
152 status = db.put(null, theKey, theData);
153 } catch (UnsupportedEncodingException e) {
154 System.out.println("putObject:[class:" + clz.getName() + "][key:"
155 + key + "][value:" + value + "]: " + e.toString());
156 e.printStackTrace();
157 }
158 return (status!=null&&status==OperationStatus.SUCCESS)?true:false;
159 }
160
161 /**
162 *
163 * @brief getData
164 * @details 获取数据
165 * @warning 其中注意事项警告
166 * @note
167 * @param key
168 * @return
169 */
170 public static String getString(String dbname, String key) {
171 String value = "";
172 Database db = getDb(dbname);
173 try {
174 DatabaseEntry keyEntry = new DatabaseEntry(key
175 .getBytes(Constant.default_charset));
176 DatabaseEntry valueEntry = new DatabaseEntry();
177 if (OperationStatus.SUCCESS == db.get(null, keyEntry, valueEntry,
178 LockMode.DEFAULT)) {
179 value = new String(valueEntry.getData(), Constant.default_charset);
180 }
181 } catch (UnsupportedEncodingException e) {
182 System.out.println("getString for key[" + key + "]: "
183 + e.toString());
184 e.printStackTrace();
185 }
186 return value;
187 }
188
189 /**
190 *
191 */
192 public static Object getObject(String dbname,Class clz,String key){
193 Database db = getDb(dbname);
194 EntryBinding binding = getBinding(db, clz);
195 Object obj = null;
196 try {
197 DatabaseEntry theKey = new DatabaseEntry(key.getBytes(Constant.default_charset));
198 DatabaseEntry theData = new DatabaseEntry();
199 OperationStatus status = db.get(null, theKey, theData,
200 LockMode.DEFAULT);
201 if (status == OperationStatus.SUCCESS) {
202 obj = binding.entryToObject(theData);
203 }
204 } catch (UnsupportedEncodingException e) {
205 System.out.println("getObject[" + clz.getName() + "] for key["
206 + key + "]: " + e.toString());
207 e.printStackTrace();
208 }
209 return obj;
210 }
211
212 /**
213 *
214 * @brief delData
215 * @details 删除数据
216 * @warning 其中注意事项警告
217 * @note
218 * @param key
219 * @return
220 */
221 public static boolean delData(String dbname,String key) {
222 Database db = getDb(dbname);
223 try {
224 DatabaseEntry keyEntry = new DatabaseEntry(key
225 .getBytes(Constant.default_charset));
226 if (OperationStatus.SUCCESS == db.delete(null, keyEntry)) {
227 return true;
228 }
229 } catch (UnsupportedEncodingException e) {
230 System.out.println("delData for key[" + key + "]: " + e.toString());
231 e.printStackTrace();
232 }
233 return false;
234 }
235
236 /**
237 *
238 * @brief clearDb
239 * @details 清空数据库
240 * @warning 其中注意事项警告
241 * @note
242 * @param dbname
243 */
244 public static void clearDb(String dbname){
245 if(databases.containsKey(dbname)){
246 Database db = databases.get(dbname);
247 db.close();
248 myEnv.truncateDatabase(null, dbname, true);
249 databases.remove(dbname);
250 System.out.println(" cleardb:"+dbname);
251 }
252 }
253
254 /**
255 *
256 * @brief foundString
257 * @details 通过key和value来同时匹配
258 * @warning 同样如果没有记录匹配key和value则会返回OperationStatus.NOTFOUND
259 * @note
260 * @param dbname
261 * @param key
262 * @param value
263 * @return
264 */
265 public static boolean foundString(String dbname, String key, String value) {
266 Database db = getDb(dbname);
267 try {
268 DatabaseEntry keyEntry = new DatabaseEntry(key
269 .getBytes(Constant.default_charset));
270 DatabaseEntry valueEntry = new DatabaseEntry(value
271 .getBytes(Constant.default_charset));
272 if (OperationStatus.SUCCESS == db.getSearchBoth(null, keyEntry,
273 valueEntry, LockMode.DEFAULT)) {
274 return true;
275 }
276 } catch (UnsupportedEncodingException e) {
277 System.out.println("foundString for key[" + key + "]: "
278 + e.toString());
279 e.printStackTrace();
280 }
281 return false;
282 }
283
284 /**
285 *
286 * @brief closeEnv
287 * @details 关闭当前数据库和数据库环境
288 * @warning 其中注意事项警告
289 * @note
290 */
291 public static void closeEnv() {
292 System.out.println("Closing env and databases");
293 bindings.clear();
294 for (Database db : databases.values()) {
295 if (db != null) {
296 try {
297 db.close();
298 } catch (DatabaseException e) {
299 System.out.println("closeDB: "+db.getDatabaseName()+" : "+ e.toString());
300 e.printStackTrace();
301 }
302 }
303 }
304 databases.clear();
305
306 if (myEnv != null) {
307 try {
308 myEnv.cleanLog();
309 myEnv.close();
310 } catch (DatabaseException e) {
311 System.out.println("closeEnv: " + e.toString());
312 e.printStackTrace();
313 }
314 }
315 }
316 }
Berkeley DB Java Edition 使用手册