Search code examples
mongodbspring-data-mongodb

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.


Solution

  • 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.