Spring Data MongoRepository保存具有不同字段数的对象

我将游戏状态存储在MongoDB数据库中,并使用Spring Data管理我的数据库交互。我是Spring Data的新手,不确定如何处理以下情况。

我有一个“游戏”类型的文档,其中包含一堆属性,例如ID,时间戳等。这些属性之一是用户采取的操作的列表。这些动作的形式为:

{ type: 2 },{type: 3,value: 4},{type: 5,id: 1234},{type 6},value: 6,id: 56}

换句话说,动作可以具有三个属性:类型,值和ID。但是,并非每个动作都需要存储所有三个值。我想避免数据库中有一堆空值,并且希望数据库不包含和id或未指定值的情况。

我不确定使用Spring Data的MongoRepository模型。我可以创建一个CRUD Game类,并将其属性之一作为action列表(其中action本身是具有属性类型,值和ID的CRUD类),但是如果这样,最终不会在数据库中存储空值我没有指定值或ID?

简而言之,我该如何使用Spring Data的MongoRepository,但仍保持灵活性,能够存储一般具有不同参数或对象类型的对象列表。

iCMS 回答:Spring Data MongoRepository保存具有不同字段数的对象

我将通过一个示例来说明如何处理不同的字段。以下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类,您需要为构造函数提供可能的组合。将适当的构造函数与idtype等一起使用。例如,创建一个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

大家都在问