我将通过一个示例来说明如何处理不同的字段。以下Game.java
POJO类表示映射到game
集合文档的对象。
public class Game {
String name;
List<Actions> actions;
public Game(String name,List<Actions> actions) {
this.name = name;
this.actions = actions;
}
public String getName() {
return name;
}
public List<Actions> getActions() {
return actions;
}
// other get/set methods,override,etc..
public static class Actions {
Integer id;
String type;
public Actions() {
}
public Actions(Integer id) {
this.id = id;
}
public Actions(Integer id,String type) {
this.id = id;
this.type = type;
}
public Integer getId() {
return id;
}
public String getType() {
return type;
}
// other methods
}
}
对于Actions
类,您需要为构造函数提供可能的组合。将适当的构造函数与id
,type
等一起使用。例如,创建一个Game
对象并保存到数据库:
Game.Actions actions= new Game.Actions(new Integer(1000));
Game g1 = new Game("G-1",Arrays.asList(actions));
repo.save(g1);
以下内容(从game
shell中查询)存储在数据库集合mongo
中:
{
"_id" : ObjectId("5eeafe2043f875621d1e447b"),"name" : "G-1","actions" : [
{
"_id" : 1000
}
],"_class" : "com.example.demo.Game"
}
请注意actions
数组。由于我们仅在id
对象中存储了Game.Actions
字段,因此仅存储了该字段。即使您指定了类中的所有字段,也只会保留带有值的字段。
这是另外两个文档,其中Game.Actions
仅使用type
创建,id + type
使用适当的构造函数创建:
{
"_id" : ObjectId("5eeb02fe5b86147de7dd7484"),"name" : "G-9","actions" : [
{
"type" : "type-x"
}
],"_class" : "com.example.demo.Game"
}
{
"_id" : ObjectId("5eeb034d70a4b6360d5398cc"),"name" : "G-11","actions" : [
{
"_id" : 2,"type" : "type-y"
}
],"_class" : "com.example.demo.Game"
}
本文链接:https://www.f2er.com/2109209.html