Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to have common method for inserting and getting objects from MongoDB collection. For all mongo db operations I am using Jongo library. Here's my code:

 public UserModel getUserByEmailId(String emailId) {
    String query = "{emailId:'"+emailId+"'}";
    Object obj = storage.get(query);

    UserModel user = (UserModel) obj; 
    //getting exception on above line. I am sure that I have UserModel 
    //type of data in obj
    // Exception is: java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to UserModel
    return user;
}

Here is "storage.get(String query)" method. My intention is to have common method to read data from mongo db. That's why I want it to return Object. (Feel free comment if I'm wrong)

public Object get(String query) {
    Object obj = collection.findOne(query).as(Object.class);
    return obj;
}

//Here: collection is my "org.Jongo.MongoCollection" type object.

What is the right way to get UserModel type of object from "Object"? Let me know if you need more information

share|improve this question

2 Answers 2

up vote 0 down vote accepted

If you only need to map documents to UserModel objects

collection.findOne("{name:'John'}").as(UserModel.class);

If you are looking for a generic approach :

public <T> T get(String query, Class<T> clazz) {
  return collection.findOne(query).as(clazz);
}
...
UserModel user = this.get("{name:'John'}", UserModel.class);
share|improve this answer

The Jongo library is returning a map, specifically a LinkedHashMap. You are trying to cast that to an instance of your UserModel class, which Java does not know how to do.

You seem to be expecting the Jongo library to return a UserModel. Assuming that's your custom designed class, there is no way that the library would know how to map the data from MongoDB to this object. Unless of course you could somehow specifically instruct it to do so (I'm not familiar with Jongo).

You could however use Jackson to map the map to UserModel (or other objects).

share|improve this answer
    
Hi Giovanni, can u give me some link where i can find some sample code of retrieving a class object from LinkedHashMap –  Amit Apr 3 '14 at 18:43
    
what do you mean? converting a map to an object? Jackson is used for that. –  Giovanni Botta Apr 3 '14 at 19:27
    
Jongo already uses Jackson to map document to POJO –  Benoît Guérout Apr 4 '14 at 12:51
    
@BenoitGuerout That should make things easier. –  Giovanni Botta Apr 4 '14 at 13:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.