从MongoDB检索值时将DBObject转换为Java对象

时间:2014-01-03 10:48:09

标签: java mongodb mongodb-java dbobject

在我的Java应用程序中,我将mongoDB中的值存储在ArrayList(Java对象集)中。 如何从DBObject中检索数据

我将数据存储在mongoDB中,如下所示:

{  "students" : [{"firstName" : "Jesse", "lastName" : "Varnell", "age" : "15", "gender" : "M" }, { "firstName" : "John", "lastName" : "Doe", "age" : "13", "gender" : "F"}] }

我正在为学生提供Java对象:

public class Student {
    public String firstName;
    public String lastName;
    public String age;
    public String gender;  // M, F      
}

我正在从mongoDB中检索数据,如:

BasicDBObject query = new BasicDBObject();
query.put("user", username); 
DBCursor cursor = theCollection.find(query); 
while (cursor.hasNext()) {
    DBObject theObj = cursor.next();
    //How to get the DBObject value to ArrayList of Java Object?
}

2 个答案:

答案 0 :(得分:12)

您可以按照以下方式执行此操作:

List<Student> students = new ArrayList<Student>();

BasicDBObject query = new BasicDBObject();
query.put("user", username); 
DBCursor cursor = theCollection.find(query); 
while (cursor.hasNext()) {
    DBObject theObj = cursor.next();
    //How to get the DBObject value to ArrayList of Java Object?

    BasicDBList studentsList = (BasicDBList) theObj.get("students");
    for (int i = 0; i < studentsList.size(); i++) {
        BasicDBObject studentObj = (BasicDBObject) studentsList.get(i);
        String firstName = studentObj.getString("firstName");
        String lastName = studentObj.getString("lastName");
        String age = studentObj.getString("age");
        String gender = studentObj.getString("gender");

        Student student = new Student();
        student.setFirstName(firstName);
        student.setLastName(lastName);
        student.setAge(age);
        student.setGender(gender);

        students.add(student);
    }               
}

答案 1 :(得分:5)

您通常使用ORM工具(尽管在非关系数据库的情况下将其称为ORM没有意义)。

有几种这样的工具。我喜欢spring-data,它为你隐藏了很多样板代码,并为你提供了一个简单,干净的语法。像这样:

@Repository
public class UserRepositoryImpl implements UserRepository {

    private MongoTemplate mongoTemplate;

    @Autowired
    public UserRepositoryImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public User findsUserByUsernameAndPassword(String userName, String encodedPassword) {
        return mongoTemplate.findOne(query(where("userName").is(userName).and("encodedPassword").is(encodedPassword)), User.class);
    }
}

User类定义为:

@Document(collection = "users")
public class User {

    private String userName;

    private String encodedPassword;

    // snip getters and setters

}