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

查看:27
本文介绍了如何将具有动态键的文档映射到 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 键进行探索,并且可以嵌套 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天全站免登陆