2

下面的代码给出了错误,它说 School 类必须实现 DBObject 接口。问题是这个接口有很多方法。我有近 100 个类,我不想编写数百万个方法。有没有简单的方法来保存对象?

DBCollection table = db.getCollection("school");

School document = new School();
table.insert(document);
4

1 回答 1

2

Instead of implementing DBObject or extending one of the existing implementations like BasicDBObject, you could have all objects which can be saved in the database have a method public DBObject toDBObject() which creates and returns a DBObject representation of the object. The BasicDBObject is a Map<String, Object> which handles the object data as key/value pairs, so it is a good candidate for this.

For a more generic solution, you could use reflection to create a method which can convert any Java object into a DBObject. To have more control over this, you could make up some annotations, add them to your classes and have your conversion method check them.

Now you have created your own object mapping framework for MongoDB. But why reinvent the wheel when others have already done it? So before you do this, check out if the existing mapping frameworks like morphia fulfill your use-case - they likely do and will save you hours of programming and weeks of debugging.

[opinion]

I usually despise object-relational mappers in the context of relational databases because of the impedance mismatch problem, but for heterogeneous databases like MongoDB they make a lot more sense, because you can store objects which have the same base-class but also some different class-specific fields in the same table collection without any ugly workarounds.

[/opinion]

于 2013-07-08T00:47:02.750 回答