8

在我的 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?
}
4

2 回答 2

13

你可以这样做:

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);
    }               
}
于 2014-01-03T11:17:56.980 回答
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

}
于 2014-01-03T11:31:49.797 回答