我是第一次使用 Spring Data 和 MongoDB。我有一个与此类似的 JSON 文档:
key: "key",
attributes: [
{
type1: [
{
class1: "class1",
genres : [
"genre1",
"genre2"
]
},
{
class2: "class2",
genres : [
"genre2",
"genre3"
]
}
]
}
]
理想情况下类型和类是动态的。可能有很多类型和类,只有作为最后的手段我才想为它们创建变量。
我知道我可以在实体类中获取“关键”字段,只需创建一个变量
String key;
和一个方法String getKey()
并使用@Field("key")
(可选)。
但是我怎样才能以我想要的格式获得整个“属性”数组:
Map\<types, Map<classes, List<genres>>>
目前我有这样的东西:
@Document("Test")
public class Test {
String key;
Map<String, Map<String, List<String>>> attributes;
@Field("key")
public String getKey() { return key; }
@Field("attributes")
public Map<String, Map<String, List<String>>> getAttributes() { return attributes; }
}
我可以通过这种方式获取地图的属性图吗?或者这是一厢情愿的想法,我实际上必须分别获取每个列表或地图以及如何做到这一点?
如果 JSON 结构也能更好地适合列表对象的映射,我可以更改它。
想通了。映射只能由大括号定义,而不能由方括号定义。
所以我的 attribute.json 文件如下所示:
"key": "key",
"attributes": {
"type1": {
"class1": {
"classValue": "example value",
"genres":[ "genre1", "genre2" ]
},
"class2": {
"classValue": "other value",
"genres":[ "genre2", "genre3" ]
}
},
"type2": {
"class3": {
"classValue": "another value",
"genres":[ "genre1", "genre2" ]
}
}
}
在我的属性类中它变成:
public class Attribute {
String key;
Map<String, Map<String, ClassDetails> attributes;
//constructor, getters, and setters
}
前两个映射键可以保存为任何字符串,这意味着我保留不同的类型和类。
为了保留班级价值和流派,我创建了一个名为 ClassDetails 的 POJO:
public class ClassDetails{
String classValue;
List<String> genres;
//constructors, getters, and setters
}
例如:下面将返回字符串“other value”
Attribute attr = mongoTemplate.findOne(query, Attribute.class);
return attr.getAttributes().get("type1").get("class2").getClassValue()