Psycho Punch
Psycho Punch

Reputation: 6892

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?

Upvotes: 6

Views: 4493

Answers (2)

Montoya
Montoya

Reputation: 31

Use @MongoId instead of @Id

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

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

Upvotes: 3

Darshan Mehta
Darshan Mehta

Reputation: 30809

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.

Upvotes: 0

Related Questions