简体   繁体   English

使用MongoDB Java将DBObject转换为POJO

[英]Converting DBObject to a POJO using MongoDB Java

I'm a starting to use MongoDb and developping a small web application that connect to this Mongo Database. 我是一个开始使用MongoDb的人,并且正在开发一个连接到此Mongo数据库的小型Web应用程序。 I have a DAO with a method to find a user from the db according to the email address assigned to the user. 我有一个DAO,它具有一种根据分配给用户的电子邮件地址从数据库中查找用户的方法。 Each user should have a unique email address so I can assume I'll get only one document. 每个用户应该有一个唯一的电子邮件地址,因此我可以假设我只会得到一个文档。 How can then convert the DBObject to a User entity? 然后如何将DBObject转换为User实体?

Here my code: 这是我的代码:

@Override
public User findUserByEmailAddress(String email) {
    DB db=MongoHelper.getDb();


    BasicDBObject query = new BasicDBObject(); 
    query.put("email", email);
    DBCollection users=db.getCollection("users");
    DBCursor cursor = users.find(query);

    DBObject user=cursor.next();

  //Code to convert the DBObject to a User and return the User
}

Thank you very much in advance! 提前非常感谢您!

DBObject is a map, so you can get required values by simply accessing it by corresponding key. DBObject是一个映射,因此您可以通过简单地通过相应键访问它来获取所需的值。

For example: 例如:

DBObject query = QueryBuilder.start("email").is(email).get();
DBCursor cursor = users.find(query);

while (cursor.hasNext()) {

   DBObject user = cursor.next();
   String firstName = (String)user.get("first_name");
   String lastName = (String)user.get("last_name");

   //TODO: use extracted properties to build User object   
}

Note that depending on document structure, the returned property can be itself a map. 请注意,根据文档结构,返回的属性本身可以是地图。 So appropriate casting is required. 因此,需要适当的铸造。 In addition, I would not assume there can be only one email per user in the document database (due to errors, wrong input etc). 此外,我不认为文档数据库中每个用户只能发送一封电子邮件(由于错误,输入错误等)。 It should be enforced on the application level. 它应该在应用程序级别上执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM