MongoJack找不到对象

时间:2016-05-30 05:38:57

标签: java mongodb mongojack

尝试使用MongoJack时,它突然开始在每个findOneById查询中返回null。即使在数据库中创建对象并且返回的ID有效。

代码

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import org.mongojack.Id;
import org.mongojack.JacksonDBCollection;
import org.mongojack.WriteResult;

public class test {

    public static void main(String[] args){
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB( "test" );

        DBCollection dbCollection = db.getCollection("myobject");
        JacksonDBCollection<MyObject, String> coll = JacksonDBCollection.wrap(dbCollection, MyObject.class,
            String.class);
        MyObject myObject = new MyObject();
        WriteResult<MyObject, String> result = coll.insert(myObject);
        String id = result.getSavedId();
        MyObject savedObject = coll.findOneById(id);

        System.out.println(savedObject);

    }

}

class MyObject{
    @Id
    private String id;
}

其输出为:

null
Process finished with exit code 0

然而,正在使用数据库中的ID创建记录。

1 个答案:

答案 0 :(得分:2)

我发现只需将@ObjectId注释添加到类id的{​​{1}}似乎可以解决问题

MyObject