_id
我的简单应用程序假设只是用to之间的映射填充 MongoDB user
。我的键 ( _id
) 是 JSON 格式,它的值很长。
{
"_id": {
"a": "1B2ac",
"b": "Windows NT 5.2; WOW64; rv:16.0 Ff/6.0"
},
"user": 1999129
}
我有几个问题:
问题 1:can's serialize class...
当我尝试插入时得到:
Caused by: java.lang.IllegalArgumentException: can't serialize class test.mongo.foo.DummyObject
at org.bson.BSONEncoder._putObjectField(BSONEncoder.java:234)
at org.bson.BSONEncoder.putObject(BSONEncoder.java:121)
at org.bson.BSONEncoder.putObject(BSONEncoder.java:86)
at com.mongodb.OutMessage.putObject(OutMessage.java:190)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:253)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:217)
at com.mongodb.DBCollection.insert(DBCollection.java:102)
at com.test.mongo.foo.DaoImpl.insertRecords(DaoImpl.java:130)
这是我的课程DummyObject
(实现Serializable
):
package test.mongo.foo;
import java.io.Serializable;
public class DummyObject implements Serializable{
private static final long serialVersionUID = -2715467675581503964L;
//default constructor
public DummyObject(){
}
private String a;
private String b;
public String getA() {
return a;
}
public String getB() {
return b;
}
public void setA(String a) {
this.a = a;
}
public void setB(String b) {
this.b = b;
}
}
这是我的DaoImp
课
package test.mongo.foo;
public class DaoImpl extends MongoDAOImpl{
public int insertRecords(List<DBObject> records) {
DBCollection coll = getDBCollection();
Exception e = null;
try {
WriteResult res = coll.insert(records);
if (res.getError() != null) {
throw new MongoRuntimeException(res.getError());
}
return res.getN();
} catch (Exception err) {
e = err;
throw new MongoRuntimeException(err);
}
}
public static DBObject convertToDBObject(DummyObject obj, long value) {
DBObject bdbo = new BasicDBObject();
bdbo.put("_id",obj);
bdbo.put("user",value);
return bdbo;
}
public static void main(String [] args){
DummyObject d = new DummyObject();
d.setA("1B2ac");
d.setB("Windows NT 5.2; WOW64; rv:16.0 Ff/6.0");
long val = 1999129;
List<DBObject> l = new ArrayList<DBObject>();
l.add(DaoImpl.convertToDBObject(d,val));
DaoImpl impl = new DaoImpl();
}
}
ISSUE 2:为避免上述问题,我尝试使用字符串到字符串映射插入记录。虽然我的输入 String (for _id
) 没有转义,DBObject
但在内部将其转义并最终写入 MongoDB,如下所示:
{
"_id": {
\"a\": \"1B2ac\",
\"b\": \"WindowsNT5.2;WOW64;rv: 16.0Ff/6.0\"
},
"user": NumberLong(1999129)
}
代替
{
"_id": {
"a": "1B2ac",
"b": "Windows NT 5.2; WOW64; rv:16.0 Ff/6.0"
},
"user": 1999129
}
关于如何解决这两个问题的任何建议?任何指针都受到高度赞赏。