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

It'*_* me 8 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"}] }
Run Code Online (Sandbox Code Playgroud)

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

public class Student {
    public String firstName;
    public String lastName;
    public String age;
    public String gender;  // M, F      
}
Run Code Online (Sandbox Code Playgroud)

我正在从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?
}
Run Code Online (Sandbox Code Playgroud)

Par*_*ade 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);
    }               
}
Run Code Online (Sandbox Code Playgroud)


Mzz*_*zzl 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

User类定义为:

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

    private String userName;

    private String encodedPassword;

    // snip getters and setters

}
Run Code Online (Sandbox Code Playgroud)

  • 不相关,但我来自未来(2022),我们称这些为ODM(对象文档映射) (2认同)