2017-04-19 187 views
0

我正在使用spring jdbc和mongoDB。我将有如下文件。 一个像MongoDB,Spring JDBC,动态密钥,映射

{ 
    "_id" : ObjectId("58f49f05c88c8f2cb8061e12"), 
    "temp" : { 
     "27" : { 
      "59" : "5" 
     }, 
     "28":{ 
      "0":"0", 
      "1":"1" 
     } 
    }, 
    "luminosity" : { 
     "27" : { 
      "59" : "3" 
     } 
    }, 
    "identifier" : 753  
} 

和其他可能会像

{ 
    "_id" : ObjectId("58f49f05c88c8f2cb8061e12"), 
    "humidity" : { 
     "27" : { 
      "59" : "5" 
     } 
    }, 
    "identifier" : 753  
} 

所以你怎么能写我的映射类此。请帮忙! 我已经写了类似

@Document(collection = "Data") 
public class Data { 

    private String identifier; 


    /** 
    * @return the identifier 
    */ 
    public String getIdentifier() { 
     return identifier; 
    } 

    /** 
    * @param identifier 
    *   the identifierto set 
    */ 
    public void setIdentifier(String identifier) { 
     this.identifier= identifier; 
    } 


    } 

我怎么能写其他领域的映射器?这是动态的

+0

你的数据结构是怪异。为什么有一个名为“27”的对象,它代表什么?如果你不能改变de datamodel你可以加载它作为json对象或linkedtreemaps。 –

+0

只是想知道下面的答案是否有帮助? – notionquest

+0

@ p.streef数字表示分钟/秒。感谢您的回复 –

回答

0

数据结构是非常规的。通常情况下,尽管MongoDB支持它,但key属性不应该是非常动态的。当您尝试使用多个管道编写复杂的聚合查询时,它可能会变得复杂。

无论如何,鉴于上述结构,可以有多种方式来定义文档模型。我使用简单的Java类(Map和String)提供了下面的解决方案。

使用简单的Map结构的原因是大多数库支持序列化过程,Java 8 Lambda函数可用于迭代和获取值。

文档类: - 使用lambda

@Document(collection = "weather") 
public class Weather { 

    @Id 
    private String id; 

    private Map<String, Map<String, String>> temp; 

    private Map<String, Map<String, String>> luminosity; 

    private String identifier; 

    public String getId() { 
     return id; 
    } 

    public Map<String, Map<String, String>> getTemp() { 
     return temp; 
    } 

    public Map<String, Map<String, String>> getLuminosity() { 
     return luminosity; 
    } 

    public String getIdentifier() { 
     return identifier; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public void setTemp(Map<String, Map<String, String>> temp) { 
     this.temp = temp; 
    } 

    public void setLuminosity(Map<String, Map<String, String>> luminosity) { 
     this.luminosity = luminosity; 
    } 

    public void setIdentifier(String identifier) { 
     this.identifier = identifier; 
    } 
} 

示例代码: -

Weather weather = mongoOperations.findById(id, Weather.class); 

     System.out.println(weather.toString()); 
     weather.getTemp().forEach((k, v) -> { 
      System.out.println("Temp : " + k + "; Values : " + v); 
     }); 
     weather.getLuminosity().forEach((k, v) -> { 
      System.out.println("Temp : " + k + "; Values : " + v); 
     });  
     System.out.println(weather.getIdentifier());