how to get inserted object id in jongo with mongodb

1k Views Asked by At

Account entity

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();}

Here I found acountIdMongo is null, don't know how to get it, here I want inserted account ObjectId.

1

There are 1 best solutions below

0
On

For me this helped:

Jongo Starter Project

Based on the above the _id in Color.java would be:

@MongoObjectId
private String _id;

and then in PersistenceHandler.java in the insert method the Object returned would contain the inserted object in the Mongo collection with _id populated.

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;
}