dozd/mongo-mapper

.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:

bildschirmfoto 2017-01-25 um 18 56 44

The same exception occurs, when I add another child.
Is it possible, that the Map<String, Child> is not recognized or mapped correctly?

dozd commented

I'll have a look at it - there is probably bug in the library as i have not test map.

dozd commented

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! 😊

dozd commented

Will have some time probably during the weekend. I'll let you know.

Thank you very much!

dozd commented

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.

dozd commented

Will be released as 1.0.8 after a while

dozd commented

Be aware that I had to increase target version to Java 8.