找不到java.lang.object的编解码器

s1ag04yj  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(300)

在maven项目中使用mongo java driver 3.12时,我在尝试存储某些POJO时遇到以下错误:
编码“\u id”时出错:找不到类java.lang.object的编解码器。
为了复制这个错误,我需要相当多的代码行,所以我在github上设置了一个项目,其中包含复制错误的代码。以下是其内容的简短版本:

public abstract class Identification {...}

public class StringID extends Identification {
    @BsonId
    private String id;
    // @BsonCreator, getId(), ...
}

public abstract class BasicDBItem<T extends Identification> {
    @BsonId
    private T id;
    @BsonCreator
    public BasicDBItem(@BsonProperty("id") T id) {
        this.id = id;
    }
    public T getId() {
        return this.id;
    }
    // ...
}

public abstract class GenericItem<T extends Identification> extends BasicDBItem<T> {
    @BsonCreator
    public GenericItem(@BsonProperty("id") T id) {
        super(id);
    }
    public abstract void foo();
}

public class SpecificItem extends GenericItem<StringID> {
    @BsonCreator
    public SpecificItem(@BsonProperty("id") StringID id) {
        super(id);
    }
}

public class App {
    public App() {
        CodecProvider pojoCodecProvider = PojoCodecProvider.builder()
                .register("stackoverflow.issues.r329433.mongodb.pojos").build();
        CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                CodecRegistries.fromProviders(pojoCodecProvider));
        /* setup mongo client */
        MongoClient client = MongoClients.create(MongoClientSettings.builder()
                .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))
                .codecRegistry(pojoCodecRegistry).build());
        MongoCollection<SpecificItem> collection = client.getDatabase("BSON-Test").getCollection("Items", SpecificItem.class);

        SpecificItem item = new SpecificItem(new StringID("Item-ID"));
        collection.insertOne(item); // error here
    }
}

mongodb文档声明泛型是完全受支持的,只要继承深度小于或等于1,泛型就似乎是正确的。所以如果你把 GenericItem 从等级制度中 SpecificItem 直接继承自 BasicDBItem 一切正常。但是在这中间添加另一个类 GenericItem 导致程序崩溃,错误如上所示。
我试图找出原因,但到目前为止我没有运气。一开始我怀疑它是由类型擦除引起的,但是根据文档,泛型应该被替换为 Identification 而不是 Object 如果我没弄错的话。
所以我不知道该怎么办。继承深度为1是非常有限的,我不想放弃我的类层次结构。由于在我最初的项目中有很多类,所以为每个类编写一个编解码器太多,而且效率非常低(更不用说这是一项大量的工作,而且可维护性非常糟糕)。
任何形式的帮助都是非常感谢的。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题