首页 > 解决方案 > 在 pojo 中存储未知对象的列表

问题描述

我想要的是

我想将带有对象列表的 pojo 作为 json 对象存储到集合中。我不知道什么对象被插入到我的 pojo 中,这就是为什么我需要让它尽可能通用。


我的方法

我使用来自 mongo db 的反应流框架。应该包含对象列表的 Pojo

public class Entity {

    public ObjectId id;
    public String type;
    public int version;

    public Set<Object> components;

    public Entity() { }
    public Entity(ObjectId id, String type, int version, Set<Object> components) {
        this.id = id;
        this.type = type;
        this.version = version;
        this.components = components;
    }
}

我作为某种测试对象创建的 pojo。

public class Chunk {

    public ObjectId id;
    public int x;
    public int y;
    public Set<ObjectId> inChunk;

    public Chunk() { }

    public Chunk(int x, int y, Set<ObjectId> entities) {
        this.x = x;
        this.y = y;
        this.inChunk= entities;
    }
}

我的主要

    public static void main(String[] args) throws Throwable {

        var pojoCodecRegistry = fromRegistries(
                MongoClientSettings.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().register(Object.class).automatic(true).build())
        );

        MongoClientSettings settings = MongoClientSettings.builder()
                .applyConnectionString(connString)
                .codecRegistry(pojoCodecRegistry)
                .retryWrites(true)
        .build();

        // Receiving database and collection
        var mongoClient = MongoClients.create(settings);
        var database = mongoClient.getDatabase("Test");
        var collection = database.getCollection("Entity", Entity.class);

        // Create an entity to fill it with components and insert it
        var entity = new Entity(new ObjectId(), "player", 1, new LinkedHashSet<>());
        var chunk = new Chunk(1,2, new LinkedHashSet<>());
        entity.components.add(chunk);

        // Insert it
        var operationSubscriber = new SubscriberHelpers.OperationSubscriber<>();
        collection.insertOne(entity).subscribe(operationSubscriber);
        operationSubscriber.await();

        // Receive it
        var printDocument = new SubscriberHelpers.PrintSubscriber<>("YO : ");
        collection.find().subscribe(printDocument);
        printDocument.await();

        mongoClient.close();
    }

问题

保存的对象正在被插入,但它缺少它的对象 ID。此外,加载后,entity.components 会被一个对象填充。但是这个对象只是来自 java 的原始“Object.class”,我不能将那个对象转换为我保存的“Chunk.class”。所以它在加载时不知何故忘记了它的类型,我无法访问它。

在此处输入图像描述 在调试器中,只加载了一个对象......不能转换为以前保存的块


我的问题

如何在我的 Entity.class 中保存“未知”对象的列表,并确保它使用以前的类型正确加载?

此外,我想知道子文档是否也可以引用其他“Entity.class”。就像在 Entity.components 中有一个“Chunk.class”,它引用了一些其他“Entity.class”对象(注意,不是子文档)。如果是这样的话,他们会自动加载吗?还是我需要自己实现?

我很高兴有任何帮助,谢谢!

标签: javamongodbmongodb-java

解决方案


推荐阅读