dozd / mongo-mapper

Easy POJO codec for MongoDB in Java
Apache License 2.0
27 stars 9 forks source link

Error casting ObjectId to String #6

Closed almostimplemented closed 7 years ago

almostimplemented commented 7 years ago
java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
    at eu.dozd.mongo.EntityCodec.decode(EntityCodec.java:95)

The error is in the if block of the following loop in EntityCodec.java:

for (String field : info.getFields()) {
    if (field.equals(info.getIdField())) {
        info.setId(t, (String) document.get(ID_FIELD));
    } else {
        Object o;
        o = document.get(field);

        if (info.getFieldType(field).isEnum()) {
            o = o == null ? null : Enum.valueOf((Class<? extends Enum>) info.getFieldType(field), (String) o);
        }
    info.setValue(t, field, o);
    }
}

Why not have the ID field be an ObjectId? Seems like that might be preferable anyway.

dozd commented 7 years ago

Can you please attach also the entity you are trying to encode / decode? I need more context when this error occurs.

dozd commented 7 years ago

I probably see. You want to have field:

@Id
ObjectId id;

instead of

@Id
String id;

Am I right?

almostimplemented commented 7 years ago

e.g.

@Entity
public class FooEntity {
  @Id
  String id;
  String foo;
}

Decoding data

{ "_id" : { "$oid" : "41b15a4bf3ca1a4ec5371c09" }, "foo" : "bar" } 

will try to cast an ObjectId to a String. I think your tests won't catch this because you only test decoding things previously encoded, and for all your ID encodings, you use String type.

dozd commented 7 years ago

Can you please check whether your issue is resolved with the latest commits? I'll release the version if so.