如何正确扩展Mongo的Document类?

时间:2015-10-25 05:34:24

标签: java mongodb

我创建了一个扩展User的课程DocumentUser只是有一些简单的构造函数和getter / setter围绕着一些字符串和整数。但是,当我尝试将User类插入Mongo时,我收到以下错误:

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class com.foo.User.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
    at org.bson.BsonDocumentWrapper.asBsonDocument(BsonDocumentWrapper.java:62)
    at com.mongodb.MongoCollectionImpl.documentToBsonDocument(MongoCollectionImpl.java:507)
    at com.mongodb.MongoCollectionImpl.insertMany(MongoCollectionImpl.java:292)
    at com.mongodb.MongoCollectionImpl.insertMany(MongoCollectionImpl.java:282)
    at com.foo.bar.main(bar.java:27)

听起来我需要使用一些Mongo Codecs的东西,但我不熟悉它,一些快速的谷歌搜索返回一些看起来非常先进的结果。

如何正确编写我的User课程以便在Mongo中使用?这是我的课程供参考:

public class User extends Document {
    User(String user, List<Document > history, boolean isActive, String location){
        this.append("_id", user)
                .append("history", history)
                .append("isActive", isActive)
                .append("location", location);
    }

    public List<Document > getHistory(){
        return this.get("history", ArrayList.class);
    }

    public void addToHistory(Document event){
       List<Document> history = this.getHistory();
        history.add(event);
        this.append("history", history);
    }

    public boolean hasMet(User otherUser){
        List<String> usersIveMet = this.getUsersMet(),
                     usersTheyMet = otherUser.getUsersMet();
        return !Collections.disjoint(usersIveMet, usersTheyMet);
    }

    public List<String> getUsersMet() {
        List<Document> usersHistory = this.getHistory();
        List<String> usersMet = usersHistory.stream()
                .map(doc -> Arrays.asList(doc.getString("user1"), doc.getString("user1")))
                .filter(u -> !u.equals(this.getUser()))
                .flatMap(u -> u.stream())
                .collect(Collectors.toList());
        return usersMet;
    }

    public String getUser(){
        return this.getString("_id");
    }
}

3 个答案:

答案 0 :(得分:12)

由于您正在尝试创建新对象(即使您从Document扩展),Mongo也无法识别它,因此您需要提供编码/解码才能让Mongo知道您的对象(至少我看不到除此之外的其他方式..)。

我玩了一下你的User类,让它运行起来。 所以,这是我定义User类的方法:

public class User {

    private List<Document> history;
    private String id;
    private Boolean isActive;
    private String location;

    // Getters and setters. Omitted for brevity..
}

然后,您需要为User类提供编码/解码逻辑:

public class UserCodec implements Codec<User> {

    private CodecRegistry codecRegistry;

    public UserCodec(CodecRegistry codecRegistry) {
        this.codecRegistry = codecRegistry;
    }

    @Override
    public User decode(BsonReader reader, DecoderContext decoderContext) {
        reader.readStartDocument();
        String id = reader.readString("id");
        Boolean isActive = reader.readBoolean("isActive");
        String location = reader.readString("location");

        Codec<Document> historyCodec = codecRegistry.get(Document.class);
        List<Document> history = new ArrayList<>();
        reader.readStartArray();
        while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
            history.add(historyCodec.decode(reader, decoderContext));
        }
        reader.readEndArray();
        reader.readEndDocument();

        User user = new User();
        user.setId(id);
        user.setIsActive(isActive);
        user.setLocation(location);
        user.setHistory(history);
        return user;
    }

    @Override
    public void encode(BsonWriter writer, User user, EncoderContext encoderContext) {
        writer.writeStartDocument();
        writer.writeName("id");
        writer.writeString(user.getId());
        writer.writeName("isActive");
        writer.writeBoolean(user.getIsActive());
        writer.writeName("location");
        writer.writeString(user.getLocation());

        writer.writeStartArray("history");
        for (Document document : user.getHistory()) {
            Codec<Document> documentCodec = codecRegistry.get(Document.class);
            encoderContext.encodeWithChildContext(documentCodec, writer, document);
        }
        writer.writeEndArray();
        writer.writeEndDocument();
    }

    @Override
    public Class<User> getEncoderClass() {
        return User.class;
    }
}

然后在开始序列化/反序列化之前需要一个用于类型检查的编解码器。

public class UserCodecProvider implements CodecProvider {

    @Override
    @SuppressWarnings("unchecked")
    public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
        if (clazz == User.class) {
            return (Codec<T>) new UserCodec(registry);
        }
        return null;
    }
}

最后,您需要向MongoClient注册您的提供商,这就是全部。

public class MongoDb {

    private MongoDatabase db;

    public MongoDb() {
        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
                CodecRegistries.fromProviders(new UserCodecProvider()),
                MongoClient.getDefaultCodecRegistry());
        MongoClientOptions options = MongoClientOptions.builder()
                .codecRegistry(codecRegistry).build();
        MongoClient mongoClient = new MongoClient(new ServerAddress(), options);
        db = mongoClient.getDatabase("test");
    }

    public void addUser(User user) {
        MongoCollection<User> collection = db.getCollection("user").withDocumentClass(User.class);
        collection.insertOne(user);
    }

    public static void main(String[] args) {
        MongoDb mongoDb = new MongoDb();

        Document history1 = new Document();
        history1.append("field1", "value1");
        history1.append("field2", "value2");
        history1.append("field3", "value3");

        List<Document> history = new ArrayList<>();
        history.add(history1);

        User user = new User();
        user.setId("someId1");
        user.setIsActive(true);
        user.setLocation("someLocation");
        user.setHistory(history);
        mongoDb.addUser(user);
    }
}

答案 1 :(得分:3)

有点晚,但偶然发现了这个问题,并且对目前提出的解决方案所涉及的工作也有些失望。特别是因为它希望保留的每个Document扩展类都需要大量的自定义代码,并且在大型数据集中也可能表现出次优的性能。

相反,我认为有人可能会背负DocumentCodec(Mongo 3.x):

public class MyDocumentCodec<T extends Document> implements CollectibleCodec<T> {

private DocumentCodec _documentCodec;
private Class<T> _class;
private Constructor<T> _constructor;

public MyDocumentCodec(Class<T> class_) {
    try {
        _documentCodec = new DocumentCodec();
        _class = class_;
        _constructor = class_.getConstructor(Document.class);
    } catch (Exception ex) {
        throw new MCException(ex);
    }
}

@Override
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
    _documentCodec.encode(writer, value, encoderContext);
}

@Override
public Class<T> getEncoderClass() {
    return _class;
}

@Override
public T decode(BsonReader reader, DecoderContext decoderContext) {
    try {
        Document document = _documentCodec.decode(reader, decoderContext);
        T result = _constructor.newInstance(document);
        return result;
    } catch (Exception ex) {
        throw new MCException(ex);
    }
}

@Override
public T generateIdIfAbsentFromDocument(T document) {
    if (!documentHasId(document)) {
        Document doc = _documentCodec.generateIdIfAbsentFromDocument(document);
        document.put("_id", doc.get("_id"));
    }
    return document;
}

@Override
public boolean documentHasId(T document) {
    return _documentCodec.documentHasId(document);
}

@Override
public BsonValue getDocumentId(T document) {
    return _documentCodec.getDocumentId(document);
}
}

然后按照

的方式注册
MyDocumentCodec<MyClass> myCodec = new MyDocumentCodec<>(MyClass.class);
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
                CodecRegistries.fromCodecs(myCodec));
MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build();
MongoClient dbClient = new MongoClient(new ServerAddress(_dbServer, _dbPort), options);

切换到这种方法,同时增加一些操作(这可能会产生很大的影响)我只是设法运行一个以前需要几个小时到30分钟的操作。解码方法可能会有所改进,但我现在主要关注的是插入。

希望这有助于某人。如果您发现此方法存在问题,请与我们联系。

感谢。

答案 2 :(得分:0)

您是否尝试在班级签名上使用@Embedded@JsonIgnoreProperties(ignoreUnknown = true)

当我遇到类似的问题时,这对我有用。我有一个模型(翻译),我存储在另一个模型(促销)的HashMap成员字段中。

一旦我将这些注释添加到翻译类签名,问题就消失了。不确定它是否会在您的情况下以这种方式工作,但值得尝试。

我必须自己探讨更多。