码迷,mamicode.com
首页 > 其他好文 > 详细

Mongo实例

时间:2016-09-13 13:35:14      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:


public class MongoHelper implements NoSqlInterface {

private static DB db = null;
private static DBCollection jxm_data = null;
private static MongoHelper instance = null;
private MongoHelper(){

}

public synchronized static MongoHelper getInstance(){
if(instance == null){
Mongo m = null;
try {
m = new Mongo(PropertyUtils.getStringVal("mongodb.host.ip"), PropertyUtils.getIntVal("mongodb.host.port"));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}

// 获取名为 test 的数据库,不存在的情况下创建
db = m.getDB("test");
//获取jxm_data DBCollection;如果默认没有创建,mongodb会自动创建
jxm_data = db.getCollection("jxm_data");

instance = new MongoHelper();
}
return instance;
}

/*
* key必须唯一
*/
public void setStringVal(String key,String value){
BasicDBObject obj = new BasicDBObject();
obj.put("key", key);
obj.put("val", value);
jxm_data.save(obj);
}

@Override
public String getStringVal(String key) {
BasicDBObject obj = new BasicDBObject();
obj.put("key", key);
DBCursor cur = jxm_data.find(obj);
if(cur.hasNext()){
return cur.next().get("val") + "";
}
return null;
}

@Override
public void setObjectVal(String key, Object obj) {
BasicDBObject o = null;
try {
o = new BasicDBObject();
o.put("key", key);
o.put("val", SerializeUtil.serializeObj(obj));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
jxm_data.save(o);
}

@Override
public Object getObjectVal(String key) {
BasicDBObject obj = new BasicDBObject();
obj.put("key", key);
DBCursor cur = jxm_data.find(obj);
if(cur.hasNext()){
try {
return SerializeUtil.unSerializeObj((byte[])cur.next().get("val"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}


@Override
public void remove(String key) {
jxm_data.remove(new BasicDBObject("key",key));
}

@Override
public void removeAll() {
jxm_data.remove(new BasicDBObject());
}

public static void main(String[] args) {
MongoHelper helper = getInstance();
// helper.setStringVal("a", "bc");
// System.out.println(helper.getStringVal("a"));;
// helper.remove("b");
// Person p = new Person(2013, "赵亮");
// helper.setObjectVal("b", p);
Person pp = (Person) helper.getObjectVal("b");
System.out.println(pp.getId()+":"+pp.getName());
}
}

Mongo实例

标签:

原文地址:http://www.cnblogs.com/biihcihc/p/5867941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!