2

账户实体

public class Account 
{       
    @MongoObjectId
    private String _id;       
    private String name;    
    public String get_id() {
        return _id;
    }    
    public void set_id(String _id) {
        this._id = _id;
    }   
    public String getName() {
        return name;
    }    
    public void setName(String name) {
        this.name = name;
    }
}

public class JongoExample {<br>
   MongoClient mongoClient = new MongoClient(); // code to connect with database
        DB db = mongoClient.getDB("kommboxj");
Jongo jongo = new Jongo(db);<br>
MongoCollection accountCollection = jongo.getCollection("account");
Account account = new Account();<br>
account.setName("rks");<br>
String accountIdMongo = (String) accountCollection.insert(account).getUpsertedId();}

这里发现acountIdMongo为null,不知道怎么获取,这里要插入账号ObjectId。

4

1 回答 1

-1

对我来说,这有帮助:

Jongo 入门项目

基于上述,Color.java中的 _id将是:

@MongoObjectId
private String _id;

然后在插入方法 中的PersistenceHandler.java中,返回的对象将包含在 Mongo 集合中插入的对象,其中填充了 _id。

public static Object insert(MongoCollection mongoCollection, Method method, Object[] args) throws Throwable {
  final Iterable<Parameter> params = Reflection.params(method, args);
  final Parameter parameter = params.iterator().next();

  Object value = parameter.getValue();
  if (value == null)
        throw new IllegalArgumentException(parameter.getType().getSimpleName() + " object is null");

  mongoCollection.insert(value);

  return value;
}
于 2016-05-02T07:16:43.803 回答