Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an java object using ReflectionDBObject class in mongodb?

I am trying to insert objects of user-defined class in java into mongodb collection.

My class is like this:

class C extends ReflectionDBObject
{
    int i;
    C(){}
}

and the code for insertion is

Mongo m = new Mongo("localhost");
com.mongodb.DB appdb = m.getDB("appdb");
DBCollection cmpcol = appdb.getCollection("feed");
DBObject bdbo = new BasicDBObject();
C c = new C();
c.i = 1;
bdbo.put("a",c);
cmpcol.insert(bdbo);

But on insertion the object is represented by a null value in the database. What am I doing wrong??I dont want to use gson or morphia.

like image 328
Arpit Solanki Avatar asked Sep 03 '12 15:09

Arpit Solanki


1 Answers

The Java driver uses getter and setter methods (not variables) on a ReflectionDBObject class to determine the properties to include in the document.

Hence your code should be:

public class C extends ReflectionDBObject
{
    int i;

    public int geti()
    {
        return i;
    }

    public void seti(int i)
    {
        this.i = i;
    }
}

This will result in an object such as the following in the collection:

{ "_id" : ObjectId("504567d903641896aa40bde6"), "a" : { "_id" : null, "i" : 1 } }

I am not aware of a means of getting rid of the "_id" : null in the sub-document. This is a characteristic of the ReflectionDBObject class. Sub-documents do not usually have _ids, but if you want a non-null _id for the subdocument, you can put the following code in your C() constructor:

public C()
{
    set_id(ObjectId.get());
}

This will result in an object such as the following:

{ 
  "_id" : ObjectId("504568ff0364c2a4a975b375"), 
  "a" : { "_id" : ObjectId("504568ff0364c2a4a975b374"), "i" : 1 } 
}

Finally, note that the geti() and seti() convention for a property "i" is slightly unusual. The JavaBeans spec says that you need getI() and setI() methods to have a property "i". However the MongoDB driver doesn't work that way for the ReflectionDBObject class.

like image 157
Ian Daniel Avatar answered Oct 27 '22 00:10

Ian Daniel