如何使用动态键将文档映射到Spring MongoDb实体类 [英] How to map document with dynamic keys to a Spring MongoDb entity class

查看:64
本文介绍了如何使用动态键将文档映射到Spring MongoDb实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以包含动态键名的文档:

I have a document that can have dynamic key names:

{
"_id" : ObjectId("51a29f6413dc992c24e0283e"),
"envinfo" : {
    "appName" : "MyJavaApp",
    "environment" : {
        "cpuCount" : 12,
        "heapMaxBytes" : 5724766208,
        "osVersion" : "6.2",
        "arch" : "amd64",
        "javaVendor" : "Sun Microsystems Inc.",
        "pid" : 44996,
        "javaVersion" : "1.6.0_38",
        "heapInitialBytes" : 402507520,
}

此处envinfo的键事先未知. 在Spring Data Mongodb中创建可映射此文档的实体类的最佳方法是什么?

Here envinfo 's keys are not known in advance. What is the best way to create an entity class in Spring Data Mongodb which will map this document?

推荐答案

这就是我要做的事情.

class EnvDocuemnt {

    @Id
    private String id; //getter and setter omitted

    @Field(value = "envinfo")
    private BasicDBObject infos;

    public Map getInfos() {
        // some documents don't have any infos, in this case return null...
        if ( null!= infos)
            return infos.toMap();
        return null;
    }

    public void setInfos(Map infos) {
        this.infos = new BasicDBObject( infos );
    }

}

通过这种方式,getInfos()返回一个Map<String,Object>,您可以在需要时使用String键进行探索,并且可以嵌套Map.

This way, getInfos() returns a Map<String,Object> you can explore with String keys when needed, and that can have nested Map.

对于您的依赖项,最好不要直接公开BasicDBObject字段,因此可以通过接口在不包含任何MongoDb库的代码中使用它.

For your dependencies, it is better not to expose the BasicDBObject field directly, so this can be used via interface in a code not including any MongoDb library.

请注意,如果envinfo中有一些经常访问的字段,那么最好将它们声明为类中的字段,以拥有直接访问器,这样就不必花费大量时间一次又一次地浏览地图

Note that if there is some frequent accessed fields in envinfo, then it would be better to declare them as fields in your class, to have a direct accessor, and so not to spend to much time in browsing the map again and again.

这篇关于如何使用动态键将文档映射到Spring MongoDb实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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