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.
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
This will explain why you'll receive that specifc type of class cast exception.