Skip to content

Cannot convert generic sub-document fields [DATAMONGO-1312] #2226

Closed
@spring-projects-issues

Description

@spring-projects-issues

Mircea Gaceanu opened DATAMONGO-1312 and commented

Precondition: Class structure with generic fields.
Expected: Generic fields should be mapped correctly.
Actual: In the following case, when I save CharFoo objects and then fetch it from DB, the generic field abstractFooField is converted back to a Character, but bar.field from the sub-document is converted to a String and not to a Character.

Data model:

@Document(collection = "foo")
public abstract class AbstractFoo<T> {

    @Id
    private String id;
    private T abstractFooField;
    private AbstractBar<T> bar;

    public AbstractFoo() {}

    public AbstractFoo(T abstractFooField, AbstractBar<T> bar) {
        this.abstractFooField = abstractFooField;
        this.bar = bar;
    }
}


public class CharFoo extends AbstractFoo<Character> {

    public CharFoo() {}

    public CharFoo(Character abstractFooField,
            AbstractBar<Character> bar) {
        super(abstractFooField, bar);
    }
}

@Document
public class AbstractBar<T> {
    public AbstractBar() {}
}

public class Bar<T> extends AbstractBar<T> {

    private T field;

    public Bar(T field) {
        this.field = field;
    }
}

Unit test:

@Test
public void givenGenericEntities_whenFindOne_thenReturnCorrectTypes() {
    // GIVEN
    Bar<Character> charBar = new Bar<>('A');
    CharFoo charFoo = new CharFoo('B', charBar);
    fooRepository.save(charFoo);

    // WHEN
    CharFoo dbCharFoo = charFooRepository.findOne(charFoo.getId());

    // THEN
    assertEquals("Field class should match", Character.class, dbCharFoo.getAbstractFooField().getClass());
    assertEquals("Field class from sub-class should match", Character.class, ((Bar) dbCharFoo.getBar()).getField()
            .getClass());
}

Result:

java.lang.AssertionError: Field class from sub-class should match 
Expected :class java.lang.Character
Actual   :class java.lang.String

MongoDB document:

{
    "_id" : ObjectId("54db485a06e70e8444a15291"),
    "_class" : "com.test.model.CharFoo",
    "abstractFooField" : "B",
    "bar" : {
        "_class" : "com.test.model.Bar",
        "field" : "A"
    }
}

I'm attaching also the test project (Intellij)


Affects: 1.8 GA (Gosling)

Reference URL: http://stackoverflow.com/questions/26630523/springdata-mongodb-convert-generic-sub-document-fields

Attachments:

Issue Links:

  • DATACMNS-783 TypeInformation should allow applying the generic context to a raw type
    ("depends on")

Backported to: 1.8.1 (Gosling SR1), 1.7.3 (Fowler SR3)

Metadata

Metadata

Assignees

Labels

in: mappingMapping and conversion infrastructuretype: bugA general bug

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions