Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Spring Data MongoDB from mapping id field as object id?

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?

like image 748
Psycho Punch Avatar asked Jun 22 '17 16:06

Psycho Punch


2 Answers

Use @MongoId instead of @Id

@MongoId(targetType = FieldType.STRING)
protected String id;

It will store String even if the "shape" is an ObjectId

like image 104
Montoya Avatar answered Nov 19 '22 20:11

Montoya


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.

like image 28
Darshan Mehta Avatar answered Nov 19 '22 20:11

Darshan Mehta