I have been trying to save and retrieve entities that have a Map object that has takes in a String and a parent class type.
For instance,
public interface MorphiaInterfaceThing {
String returnsAString();
}
I would then have a class implementing MorphiaInterfaceThing .
@Embedded
public class MorphiaTest implements MorphiaInterfaceThing {
private String stringReturn = "Test"
@Override
public String returnsAString() {
return stringReturn;
}
}
Then, I would have an entity that holds a Map<String, InterfaceExample>.
@Entity
public class SampleEntity {
@Embedded
private Map<String, InterfaceExample> map
public void test() {
map.put("TestKey", new MorphiaTest());
}
}
I then instantiate the object and ran SampleEntity#test(). When saving the entity, with Datastore#save(obj), it works fine. It saved the entity into a document.
However, when I tried to retrieve the SampleEntity from the database via morphia, it threw a java.lang.RuntimeException: org.mongodb.morphia.mapping.MappingException: No usable constructor.
After a little testing like changing the generic tyoe of the map from Map<String, InterfaceExample> to Map<String, MorphiaTest>, I ultimately presumed the issue is due to the fact that morphia tries to instantiate from the given generic type (In this case, MorphiaInterfaceThing) rather than the actual class type (MorphiaTest) stored in the document. Since MorphiaInterfaceThing is an interface, it does not have a constructor and therefor throws the exception.
My question now is, how am I able to force morphia to call upon the actual object stored in the map, in the document rather than the generic type itself (i.e. method, annotation etc)? If that is not possible, are there any other alternatives to accomplishing what I am trying to do (In this case, storing a map of some kind which has a generic of the parent class)?
Also, I am sorta new to Morphia so any other advice in regards to Morphia would be greatly appreciated!
What version of morphia are you on? If you pass useDiscriminator=true
on your @Embedded
declaration that should give morphia enough info to load your types.