morphia icon indicating copy to clipboard operation
morphia copied to clipboard

Can I map arbitrary object as @Id of an entity?

Open seoj opened this issue 10 years ago • 7 comments

Example:

@Entity
public class File
{
    @Id
    public FileKey fileKey;

    public String directory;

    public String filePath;

    public Long fileSizeBytes;
}

When I try to save, I get an error:

java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to com.mongodb.DBObject

seoj avatar May 06 '16 19:05 seoj

Actually i'm also facing the same issue. My use case is somewhat different. If the client passes in an id then i need to use that as the _id. However if the client doesnt pass in an id then i need to use ObjectID can only have an ObjectID or the String id as the _id and not both.

For this i define my @Id as java.lang.Object and i get the same exception. After debugging i found that the error is caused here.

In normal flow if we defined the @Id as ObjectId, the expression mf.isTypeMongoCompatible() is true and uses a different Mapper (ValueMapper)

Is it possible to fix this based on the instance of the Object type for the _id?

nitinkcv avatar May 18 '16 04:05 nitinkcv

@seoj what happens when you put @Embedded on that field?

@nitinkcv mapping fields of type Object is not currently supported. I'd suggest your ID field should be a String and when you generate an ObjectID just toString() it before assigning it to the ID field. then your IDs will always be a String and there'd be no conflict.

evanchooly avatar May 25 '16 13:05 evanchooly

Thanks. When do you think this can be supported? If you don't have time i can work on a PR when i get time.

nitinkcv avatar May 25 '16 19:05 nitinkcv

There aren't plans currently to support that. With Object, there's nothing we can track to map the serialization data properly. In short, we can't tell how we're supposed to serialize it or how to read it out of the database.

evanchooly avatar May 25 '16 20:05 evanchooly

@evanchooly I am unable to reproduce the issue for some reason. I did not need the @Embedded annotation on the field for it to work though.

seoj avatar May 25 '16 20:05 seoj

@seoj OK. I'll close this then. If you run in to it again, please post to the mailing list and we'll take a look.

evanchooly avatar May 25 '16 20:05 evanchooly

FWIW, to support a union type for an @Id field, I had success adding a custom TypeConverter (must implement SimpleValueConverter) that simply passes through Object values. I could definitely see this being error prone so obviously use with caution / add appropriate error handling.

alechenninger avatar Dec 08 '17 20:12 alechenninger