如何将最终字段添加到现有的spring-data-mongodb文档集合中? [英] How to add a final field to an existing spring-data-mongodb document collection?

查看:177
本文介绍了如何将最终字段添加到现有的spring-data-mongodb文档集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 spring-data-mongodb 版本 1.0.2.RELEASE

@Document
public class Snapshot {
    @Id
    private final long id;
    private final String description;
    private final boolean active;

    @PersistenceConstructor
    public Snapshot(long id, String description, boolean active) {
        this.id = id;
        this.description = description;
        this.active = active;
    }
}

我正在尝试添加新房产 private final boolean billable; 。由于属性是 final ,因此需要在构造函数中设置它们。如果我将新属性添加到构造函数中,则应用程序将无法再读取现有文档。

I'm trying to add a new property private final boolean billable;. Since the properties are final they need to be set in the constructor. If I add the new property to the constructor, then the application can no longer read the existing docs.

org.springframework.data.mapping.model.MappingInstantiationException: Could not instantiate bean class [com.some.package.Snapshot]: Illegal arguments for constructor;

据我所知,你不能将多个构造函数声明为 @ PersistenceContstructor 所以除非我手动更新现有文档以包含 billable 字段,否则我无法添加 final 此现有集合的属性。

As far as I can tell, you cannot have multiple constructors declared as @PersistenceContstructorso unless I manually update the existing documents to contain the billable field, I have no way to add a final property to this existing collection.

之前有没有人找到解决方案?

Has anyone found a solution to this before?

推荐答案

我发现只能使用私有最终字段添加到现有集合中> @PersistenceContstructor 注释。相反,我需要添加 org.springframework.core.convert.converter.Converter 实现来为我处理逻辑。

I found that it is not possible to add a new private final field to an existing collection using only the @PersistenceContstructor annotation. Instead I needed to add an org.springframework.core.convert.converter.Converter implementation to handle the logic for me.

这是我的转换器最终看起来像:

Here's what my converter ended up looking like:

@ReadingConverter
public class SnapshotReadingConverter implements Converter<DBObject, Snapshot> {

    @Override
    public Snapshot convert(DBObject source) {
        long id = (Long) source.get("_id");
        String description = (String) source.get("description");
        boolean active = (Boolean) source.get("active");
        boolean billable = false;
        if (source.get("billable") != null) {
            billable = (Boolean) source.get("billable");
        }
        return new Snapshot(id, description, active, billable);
    }
}

我希望将来可以帮助其他人。

I hope this can help someone else in the future.

这篇关于如何将最终字段添加到现有的spring-data-mongodb文档集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆