有没有办法自动创建 Mongo 编解码器?

cae*_*eus 4 java asynchronous codec mongodb

我愿意将我的代码从 mongojack 迁移到支持新的异步 mongo 驱动程序的代码。然而我发现编码/解码的新方法是通过Codecs 并且我不认为自己Codec为模型中的每个类编写 。这就是为什么我宁愿编写一个库,给定一个类创建一个Codec. 然而我不知道如何做到这一点,也不知道是否已经有人做出一些努力来实现同样的目标。有一些库可以实现我想要的吗?如果没有,实现它的最佳方法是什么。

(我知道我可能应该使用CodecProvider那里的某个地方,但我仍然不知道从哪里开始)

Kev*_*Day 5

以下是我们解决这个问题的方法(最终结果是 Lombok、Jackson 和 MongoDB 之间的超级流畅):

提供商:

public class JacksonCodecProvider implements CodecProvider {
    private final ObjectMapper objectMapper;

    public JacksonCodecProvider(final ObjectMapper bsonObjectMapper) {
        this.objectMapper = bsonObjectMapper;
    }

    @Override
    public <T> Codec<T> get(final Class<T> type, final CodecRegistry registry) {

            return new JacksonCodec<>(objectMapper, registry, type);

    }
}
Run Code Online (Sandbox Code Playgroud)

以及编解码器本身:

class JacksonCodec<T> implements Codec<T> {
    private final ObjectMapper objectMapper;
    private final Codec<RawBsonDocument> rawBsonDocumentCodec;
    private final Class<T> type;

    public JacksonCodec(ObjectMapper objectMapper,
                        CodecRegistry codecRegistry,
                        Class<T> type) {
        this.objectMapper = objectMapper;
        this.rawBsonDocumentCodec = codecRegistry.get(RawBsonDocument.class);
        this.type = type;
    }

    @Override
    public T decode(BsonReader reader, DecoderContext decoderContext) {
        try {

            RawBsonDocument document = rawBsonDocumentCodec.decode(reader, decoderContext);
            String json = document.toJson();
            return objectMapper.readValue(json, type);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public void encode(BsonWriter writer, Object value, EncoderContext encoderContext) {
        try {

            String json = objectMapper.writeValueAsString(value);

            rawBsonDocumentCodec.encode(writer, RawBsonDocument.parse(json), encoderContext);

        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public Class<T> getEncoderClass() {
        return this.type;
    }
}
Run Code Online (Sandbox Code Playgroud)

当与 Lombok 和最新的 Jackson 注释结合使用时,它允许我们做这样的事情(看起来几乎不像 Java 代码,是吗?):

@JsonIgnoreProperties(ignoreUnknown=true)
@JsonDeserialize(builder = Account.AccountBuilder.class)
@Builder(toBuilder=true)
@Value
public class Account {

    @JsonProperty private String _id;
    @JsonProperty private long _version;
    @JsonProperty private String organizationName;

    @JsonPOJOBuilder(withPrefix = "")
    public static final class AccountBuilder {
    }

}
Run Code Online (Sandbox Code Playgroud)

然后:

Account account = collection.find(eq("_id", id)).first();
System.out.println(account.getOrganizationName());
Run Code Online (Sandbox Code Playgroud)