Can I map arbitrary object as @Id of an entity?
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
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?
@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.
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.
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 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 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.
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.