How to add a final field to an existing spring-data-mongodb document collection?

放肆的年华 提交于 2019-12-06 13:54:52

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!