【发布时间】:2014-04-03 17:40:32
【问题描述】:
我想有一个通用的方法来从 MongoDB 集合中插入和获取对象。对于所有 mongo db 操作,我使用的是 Jongo 库。这是我的代码:
public UserModel getUserByEmailId(String emailId) {
String query = "{emailId:'"+emailId+"'}";
Object obj = storage.get(query);
UserModel user = (UserModel) obj;
//getting exception on above line. I am sure that I have UserModel
//type of data in obj
// Exception is: java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to UserModel
return user;
}
这里是“storage.get(String query)”方法。我的意图是使用通用方法从 mongo db 读取数据。这就是为什么我希望它返回 Object。 (如有错误欢迎评论)
public Object get(String query) {
Object obj = collection.findOne(query).as(Object.class);
return obj;
}
//Here: collection is my "org.Jongo.MongoCollection" type object.
从“对象”获取 UserModel 类型对象的正确方法是什么?如果您需要更多信息,请告诉我
【问题讨论】: