MongoDB,Spring JDBC,动态密钥,映射

时间:2017-04-19 09:25:49

标签: mongodb dynamic field spring-jdbc

我正在使用spring jdbc和mongoDB。我将有如下文件。 一个就像

{
    "_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;
    }


    }

如何为其他字段编写映射器?这是动态的

1 个答案:

答案 0 :(得分:0)

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

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

使用简单Map结构的原因是大多数库都支持序列化过程,Java 8 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;
    }
}

使用Lambda的示例代码: -

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