dozd / mongo-mapper

Easy POJO codec for MongoDB in Java
Apache License 2.0
27 stars 9 forks source link

.get() on Map and casting to the class which is used in the Map leads to ClassCastException #4

Closed Pokerkoffer closed 7 years ago

Pokerkoffer commented 7 years ago

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 7 years ago

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

dozd commented 7 years ago

Ok, it's quite complicated issue. I've found a way but it takes some time to implement and test.

Pokerkoffer commented 7 years ago

ok, thank you very much for your effort!

Pokerkoffer commented 7 years ago

any updates on this? Thanks! 😊

dozd commented 7 years ago

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

Pokerkoffer commented 7 years ago

Thank you very much!

dozd commented 7 years ago

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 7 years ago

Will be released as 1.0.8 after a while

dozd commented 7 years ago

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