SpringData MongoDB - 转换通用子文档字段

时间:2014-10-29 12:36:01

标签: java mongodb generics spring-data spring-data-mongodb

在以下情况中,当我保存 CharFoo 对象然后执行查找时,通用字段 abstractFooField 将转换回字符,但子文档中的 bar.field 将转换为字符串而不是字符 难道我做错了什么?或者Spring Data MongoDB不支持这个?

P.S:我使用的是spring-data-mongodb 1.6.0.RC1和spring-data-commons 1.9.0.RC1

@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;
    }
}

单元测试:

@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());
}

结果:

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

MongoDB文档:

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

1 个答案:

答案 0 :(得分:0)

这是由spring-data-mongodb 1.8.1

中的DATAMONGO-1312解决的