I am developing my first Java, MongoDB, Morphia application and cannot solve the following exception:-

java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.DBObject
    at org.mongodb.morphia.mapping.EmbeddedMapper.fromDBObject(EmbeddedMapper.java:74)
    at org.mongodb.morphia.mapping.Mapper.readMappedField(Mapper.java:797)
    at org.mongodb.morphia.mapping.Mapper.fromDb(Mapper.java:250)
    at org.mongodb.morphia.mapping.Mapper.fromDBObject(Mapper.java:191)
    at org.mongodb.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:134)
    at org.mongodb.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:146)
    at org.mongodb.morphia.query.MorphiaIterator.next(MorphiaIterator.java:117)
    at org.mongodb.morphia.query.QueryImpl.asList(QueryImpl.java:150)
    at test.DatabaseManagerTest.testListParent(DatabaseManagerTest.java:172)

My Tech Stack is as follows:-

Java 8 jdk1.8.0_112
Morphia 1.2.1
Mongo java driver 3.2.2

My Parent Entity class:-

@Entity("parent")
public class Parent {

    @Id
    private ObjectId id;

    @Indexed(options = @IndexOptions(unique = false))
    private Child child;

    private String comment;

    private Date updateTimestamp;

}

My Child entity:-

@Embedded
public class Child {

    private int value;
    private String name;
}

The JUNIT code that fails:-

final Datastore datastore = DatabaseManager.getDatastore();

final Query<Parent> query = datastore.createQuery(Parent.class);
final List<Parent> parents = query.asList(); <<<< EXCEPTION OCCURS HERE

for (Parent parent : parents) {
    Assert.assertNotNull(parent);
}

What mistake have I made in annotating my two entity classes?

I guess its related to the embedded Child class as the stack trace mentions org.mongodb.morphia.mapping.EmbeddedMapper.

What I find strange is that I havent chnaged the Parent and/or Child class in anyway, and all my tests used to pass fine.

Today I re run my tests and they have started throwing this exception.

2

There are 2 answers

2
s7vr On BEST ANSWER

I think the problem is the data stored in child field. You have some bad data. If I have to guess as I can't look at data you've a child field with data like

"child" : "somestring"

This will explain why you'll receive that specifc type of class cast exception.

0
r3dge On

I encountered the same problem. I think that mongo does not consider a string datatype as an object. If the data stored in mongo is of type string while the associated Java variable is typed as Object then the variable can not be cast and this exception is thrown.

In my case, the issue was that I placed an ArrayList<String> in an Object variable and that morphia inserted it into Mongo as a String (an ArrayList with a single value seems to be interpreted as a single string). The causes an exception which prevents the loading of the Java object.