Converting DBObject to Java Object while retrieve values from MongoDB

假装没事ソ 提交于 2019-12-03 13:46:47

You can do it as follows :

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);
    }               
}

You generally use an ORM tool for that (though it wouldn't be meaningful to call it ORM in the case of a non relational database).

There are several such tools. I like spring-data, which hides a lot of boiler plate code for you and gives you a simple, clean syntax. Something like this:

@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);
    }
}

With the User class defined as:

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

    private String userName;

    private String encodedPassword;

    // snip getters and setters

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!