I have set up my own mechanism for assigning identities to my domain objects, and so when persisting them, there really isn't much value for me to keep track of what MongoDB assigns to them. However, I name the identity fields for my domain classes id
because, well, it's concise and understandable. The problem is that, according to the documentation, Spring will automatically map this field to MongoDB's assigned ObjectID. How do I prevent this from happening without having to rename my id field, or defining a custom identity field annotated with @Id
just for the sake of working around this?
Use @MongoId instead of @Id
@MongoId(targetType = FieldType.STRING)
protected String id;
It will store String even if the "shape" is an ObjectId
Well, you can't do that with Spring data I am afraid. Mongodb (and in turn, Spring data) needs a field to uniquely identify each document
. If you have an id
field already, and if it's unique for each and every object then yes, you can annotate it with @Id
and mongo will take care of the rest.
If not, you will have to create a new field and map it to _id
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With