How to map document with dynamic keys to a Spring MongoDb entity class

有些话、适合烂在心里 提交于 2019-12-01 03:33:20

问题


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,
}

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?


回答1:


This is one way of doing it. There may be other better ways.

Create a map of attributes and store the map in mongo.

public class Env {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private ObjectId id;
    @Field
    private Envinfo envinfo;

    public static class Envinfo {
       @Field
       private String appName;
       @Field
       private Map<String, String> attributes;
    }
}

If you know the keys in advance, you may add those attributes in Envinfo and keep those out of attributes map.




回答2:


Here is what I'll do.

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

}

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

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.

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.



来源:https://stackoverflow.com/questions/17899872/how-to-map-document-with-dynamic-keys-to-a-spring-mongodb-entity-class

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