0

我正在尝试使用 quarkus-mongodb-panache 将 JSONArray 存储和检索到 mongo db。

import io.quarkus.mongodb.panache.MongoEntity;
import io.quarkus.mongodb.panache.PanacheMongoEntity;
import org.json.simple.JSONArray;

@MongoEntity(collection="data")
public class A extends PanacheMongoEntity {
    public LocalDate insertTime;
    public JSONArray data;

    public static void save(A a) {
        persist(a);
    }

    public static A findByDate(LocalDate localDate) {     
        return find("insertTime", localDate).firstResult();
    }
}

我能够将 JSONArray 存储到 mongodb 并且无法检索它。我在阅读 mongodb 条目时遇到下面提到的错误。

Resulted in: org.bson.codecs.configuration.CodecConfigurationException: Unable to set value for property 'data' in A
    at org.bson.codecs.pojo.PropertyAccessorImpl.setError(PropertyAccessorImpl.java:74)
    at org.bson.codecs.pojo.PropertyAccessorImpl.set(PropertyAccessorImpl.java:60)
    ... 97 more
Resulted in: org.bson.codecs.configuration.CodecConfigurationException: Failed to decode 'A'. Decoding 'data' errored with: Unable to set value for property 'data' in A
    at org.bson.codecs.pojo.PojoCodecImpl.decodePropertyModel(PojoCodecImpl.java:225)
    ... 95 more
Resulted in: org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec.
Decoding into a 'A' failed with the following exception:

Failed to decode 'A'. Decoding 'data' errored with: Unable to set value for property 'data' in A

A custom Codec or PojoCodec may need to be explicitly configured and registered to handle this type.
    at org.bson.codecs.pojo.AutomaticPojoCodec.decode(AutomaticPojoCodec.java:40)
    ... 91 more
Resulted in: org.jboss.resteasy.spi.UnhandledException: org.bson.codecs.configuration.CodecConfigurationException: An exception occurred when decoding using the AutomaticPojoCodec.

我认为如果我提供 mongo-jackson-codec 可以解决这个问题。但是如何在 mongodb-panache 中注册编解码器?

4

1 回答 1

0

带有 Panache 的 MongoDB 使用能够自动将 POJO 转换为 BSON 对象的自动 pojo 编解码器。

如果您的 POJO 无法转换(在这种情况下由于 JSONArray 属性),您应该为其提供编解码器,我们的 mongodb 客户端支持将自动注册找到的任何 MongoDB 编解码器,请参阅使用 BSON 编解码器简化 MongoDB 客户端使用

在这里,我认为您需要注册一个 condec 来处理 JSONArray 类型。

更新:由于编解码器位于外部库中,因此该外部库需要由 Jandex 索引,以便具有 Panache 扩展的 MongoDB 发现编解码器。

为了能够索引外部库,您可以在 application.properties 文件中使用以下属性:

quarkus.index-dependency.mongo-jackson-codec.group-id=fr.javatic.mongo
quarkus.index-dependency.mongo-jackson-codec.artifact-id=mongo-jackson-codec

有关如何索引依赖项的更多信息,请参阅CDI 参考指南中的如何生成 Jandex 索引

于 2021-05-10T08:05:46.670 回答