![](/img/trans.png)
[英]How to map document with dynamic keys to a Spring MongoDb entity class
[英]How to Map JSON with dynamic keys on MongoDB Entity for Spring Data MongoDB?
大家?
我有一个具有以下结构的JSON:
{
"Recife": {
"coordenadas": {
"upperLeft": {
"x": 0,
"y": 1000
},
"bottomRight": {
"x": 600,
"y": 500
}
}
}
}
{
"Cuiaba": {
"coordenadas": {
"upperLeft": {
"x": 0,
"y": 1000
},
"bottomRight": {
"x": 600,
"y": 500
}
}
}
}
{
"Santos": {
"coordenadas": {
"upperLeft": {
"x": 0,
"y": 1000
},
"bottomRight": {
"x": 600,
"y": 500
}
}
}
}
上面的代码代表了存储在我的MongoDB中的三个文档示例。
请注意,键(Recife,Cuiabá和Santos)在此模式中是动态的。
我的问题是如何使用Spring Data MongoDB在实体中映射这些动态键? 我尝试了以下方法:
@Id
private String id;
@Field
private Map<String, Cidades> map;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Cidades> getMap() {
return map;
}
public void setMap(Map<String, Cidades> map) {
this.map = map;
}
但是当Spring Repository进行查询时,map变量返回null。
我的代码有什么问题?
最好的祝福。
不,你不能。 如果要将这些文档映射到对象,则应具有静态键。 可能的解决方案是使用简单的操作检索文档:
Iterable<BasicDBObject> objects = mongoOperations.find(query, BasicDBObject.class, "collection");
然后将其手动转换为您的对象。
objects.stream()
.map(obj -> new Entity(...)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.