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

前端 未结 2 1072
予麋鹿
予麋鹿 2021-01-13 03:10

I have a document that can have dynamic key names:

{
\"_id\" : ObjectId(\"51a29f6413dc992c24e0283e\"),
\"envinfo\" : {
    \"appName\" : \"MyJavaApp\",
    \         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 03:29

    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 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.

提交回复
热议问题