Frage

I have this type of records present inside my collection

{
    "_id": {
        "$oid": "537470dce4b067b395ba47f2"
    },
    "symbol": "CMC",
    "tvol": 76.97
}

While retrieving results , i am unable to map to to my custom object This is my client program

public class Data {
    public static void main(String[] args) {
        try {

            String textUri = "mongodb://admin:password1@ds043388.mongolab.com:43388/stocks";
            MongoURI uri = new MongoURI(textUri);
            Mongo m = new Mongo(uri);
            DB db = m.getDB("stocks");
            DBCollection table = db.getCollection("stock");
            BasicDBObject searchQuery = new BasicDBObject();
            DBCursor cursor = table.find(searchQuery);
            while (cursor.hasNext()) {
            Security sec = (Security) cursor.next();
            System.out.println(sec.getSymbol());
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }

    }
}

Security.java

package com;

import com.mongodb.BasicDBObject;

public class Security extends BasicDBObject {

    public Security() {

    }

    private String symbol;

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

}

This is the exception i am getting .

Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.Security
    at com.Data.main(Data.java:25)
War es hilfreich?

Lösung

You need to tell the driver what class to instantiate, try adding this line before you run your find():

table.setObjectClass(Security.class);

Your getters on your Security class aren't really complete here, you'd need to do something like this:

public String getSymbol() {
   return getString("symbol");
}

Andere Tipps

When MongoDB Driver returns it return as BasicDBObject for an Object by default which is kind of Map.

if you want to retrive as your own Java POJO , you have to implement DbObject Interface

Reference

You are extending BasicDBObject which is internally implementing DBObject , so you are fine in that context.

However you have explicitly tell to Mongo to return as Security as

collection.setObjectClass(Security.class); 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top