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

前端 未结 2 1091
予麋鹿
予麋鹿 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:26

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

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

提交回复
热议问题