.get() on Map and casting to the class which is used in the Map leads to ClassCastException
Closed this issue · 9 comments
Hi,
i have the following code:
Parent:
@Entity
public class Parent {
@Id
private String id;
private Map<String, Child> childs;
// getter, setter
}
Child:
@Embedded
public class Child {
private String name;
// getter, setter
}
Main:
public static void main(String[] args) {
// ...
Parent parent = new Parent();
parent.setId("parent1");
Child child = new Child();
child.setName("child1");
parent.setChilds(new HashMap<String, Child>());
parent.getChilds().put(child.getName(), child);
mapperTest.insertOne(parent);
Parent parent2 = mapperTest.find().first();
Map<String, Child> children = parent2.getChilds();
Child child1 = children.get(child.getName()); // <- ClassCastException
}
The following Json is inserted into mongoDB:
{
"_id" : "parent1",
"childs" : {
"child1" : {
"name" : "child1"
}
}
}
The following code throws a ClassCastException:
Exception in thread "main" java.lang.ClassCastException: org.bson.Document cannot be cast to Child
When i inspect the class parent2
(the one that is filled with the values read from the db) the values of Map childs
are of type bson.Document
and not Child
. See screenshot below:
The same exception occurs, when I add another child.
Is it possible, that the Map<String, Child> is not recognized or mapped correctly?
I'll have a look at it - there is probably bug in the library as i have not test map.
Ok, it's quite complicated issue. I've found a way but it takes some time to implement and test.
ok, thank you very much for your effort!
any updates on this? Thanks! 😊
Will have some time probably during the weekend. I'll let you know.
Thank you very much!
Simple Maps are working. I'll have to do some refactoring do enable also maps like Map<String, List<EntityRef>>
and similar more complex with "inner" generics.
Will be released as 1.0.8 after a while
Be aware that I had to increase target version to Java 8.