首页 > 代码库 > Mongo实例
Mongo实例
public class MongoHelper implements NoSqlInterface {
private static DB db = null;
private static DBCollection jxm_data = http://www.mamicode.com/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 = http://www.mamicode.com/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实例