在mongodb中使用ReflectionDBObject类插入一个java对象? [英] Inserting an java object using ReflectionDBObject class in mongodb?

查看:610
本文介绍了在mongodb中使用ReflectionDBObject类插入一个java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在java中将用户定义类的对象插入到mongodb集合中。

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

我的类是这样的:

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

/ p>

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

但在插入时,对象由数据库中的空值表示。我不想使用gson或morphia。

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.

推荐答案

Java驱动程序使用getter和setter方法

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



我不知道如何摆脱< c $ c>_ id:null 。这是ReflectionDBObject类的一个特性。子文档通常没有_ids,但是如果你想要一个非空的_id为子文档,你可以把下面的代码在你的C()构造函数:

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

属性i的 geti() seti()约定略有不同。 JavaBeans规范说,您需要具有属性i的 getI() setI()方法。但是MongoDB驱动程序对ReflectionDBObject类不起作用。

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.

这篇关于在mongodb中使用ReflectionDBObject类插入一个java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆