Munichong
Munichong

Reputation: 4031

How cast DBObject retrieved from MongoDB to customized class?

In my project, I make a class called ClickScoreTuple which extends BasicDBObject. (Otherwise it will have Serielizable problem).

Then, I use the below code to insert a ClickScoreTuple

public void insertToMongodb(String q, ClickScoreTuple cs){

    BasicDBObject doc = new BasicDBObject();
    doc.put("query", q);
    doc.put("clicks", cs);
    coll.insert(doc);
}

And use the below code to retrieve data from MongoDB.

public ClickScoreTuple retrieveFromMongodb(String q){

    BasicDBObject query = new BasicDBObject();

    query.put("query", q);
    DBCursor cursor = coll.find(query);

    **ClickScoreTuple result = (ClickScoreTuple) cursor.next();**
    cursor.close();
    return result;
}

However, I get such problem:

Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to ClickScoreTuple
at MongoDBManager.retrieveFromMongodb(MongoDBManager.java:50)
at UserLogHistoryProcessor.processLogHistory(UserLogHistoryProcessor.java:30)
at UserLogHistoryProcessor.main(UserLogHistoryProcessor.java:108)

Does anyone know hoe to solve it?

Upvotes: 1

Views: 2962

Answers (2)

Sudipta Ghorui
Sudipta Ghorui

Reputation: 159

You need to set the Object Class type.... Use setObjectClass method of DBCollection before saving and retrieving the object .... In your case, it should be --

coll.setObjectClass(ClickScoreTuple.class);

Upvotes: 1

Aravind Yarram
Aravind Yarram

Reputation: 80166

Parent can hold a reference to child but not vice versa. You have to map DBObject manually to ClickScoreTuple as the DBCursor.next() method was not coded to return your child.

Upvotes: 0

Related Questions