Uploaded image for project: 'Spring Data Commons'
  1. Spring Data Commons
  2. DATACMNS-1196

Failing generic type resolution of generic types within nested generic fields




      It seems that the type resolution is not working properly when having nested object composition with generic type.
      Example of model: constructors, getters,... ommited

      public class Outer {
      	private Generic<?> generic;
      public enum MyEnum {
      	E1, E2
      public abstract class Generic<T> {
      	private Inner<T> inner;
      	public static class EnumGeneric extends Generic<MyEnum> {
      public class Inner<T> {
      	private T elem;
      	private List<T> myList;

      And create instance of Outer with

      Outer outer = new Outer(new EnumGeneric(new Inner<>(
          MyEnum.E1, Arrays.asList(MyEnum.E1, MyEnum.E2)

      When we create an instance of Outer which has reference to instance of Generic whose generic type is MyEnum then if we save Outer instance using MongoTemplate it's persisted in db correctly converted to mongo's document.

        "generic" : {
          "inner" : {
            "elem" : "E1",
            "myList" : ["E1", "E2"]
          "_class" : "my.pckg.Generic$EnumGeneric"
        "_class" : "my.pckg.Outer"

      But, when we try to read it from db it is mapped incorrectly back to Outer. Field myList in instance of Inner contains a List which contains instances of String, but field elem in instance of Inner is mapped correctly and it really contains an instance of MyEnum. Seems that problem is in MongoConverter. I'm attaching a simple project which is able to reproduce problem described above. In tests, I'm not actually storing an instance to mongo collection, but rather using only MongoConverter to convert an instance to Document and than back to Outer. I don't know if workaround for this cold be writing a custom Converter.
      My workaround for this (in real project) was to manually convert a Document to some domain specific instance, but that is really annoying. I know that mapping from mongo types back can be tricky and sometimes type information is lost, but that is not case here. For comparison, I've tried Jackson's ObjectMapper to do serialization of instance of Outer to JSON string and than de-serialize JSON on back to Outer and it seems that Jackson resolves generic types correctly.




            olivergierke Oliver Drotbohm
            atomac Antonio Tomac
            Last updater:
            Oliver Drotbohm
            0 Vote for this issue
            2 Start watching this issue