Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring data mongodb _id mapping preference

I am using spring data mongodb framework in my java application to persist my application data in mongodb. In my java model class I have two fields.

1) A field objId with @Id annotation on it. 2) A field id

with respect to mapping to _id key in the mongodb document saved, which one will get preference or will I get an error for multiple mapping. I am using spring data mongo 1.6.1. I know I could have tested this out but I do not have local environment setup.

like image 463
Vignesh Kumar Avatar asked Dec 09 '14 19:12

Vignesh Kumar


2 Answers

you can use @Field("id") to disable map id field to _id

like image 57
ChuanKai Liu Avatar answered Sep 28 '22 09:09

ChuanKai Liu


The answer is in documentation http://docs.spring.io/spring-data/data-mongo/docs/1.7.0.M1/reference/html/

MongoDB requires that you have an '_id' field for all documents. If you don’t provide one the driver will assign a ObjectId with a generated value. When using the MongoMappingConverter there are certain rules that govern how properties from the Java class is mapped to this '_id' field.

The following outlines what property will be mapped to the '_id' document field:

A property or field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field.

A property or field without an annotation but named id will be mapped to the '_id' field.

As you can see @Id (objId) will take precedence.

like image 34
Michal Wilkowski Avatar answered Sep 28 '22 08:09

Michal Wilkowski