spring data mongdb id 策略

272 阅读2分钟

docs.spring.io/spring-data…

11.5.1. How the _id Field is Handled in the Mapping Layer

MongoDB requires that you have an _id field for all documents. If you do not provide one, the driver assigns an ObjectId with a generated value. When you use the MappingMongoConverter, certain rules govern how properties from the Java class are mapped to this _id field:

  1. A property or field annotated with @Id (org.springframework.data.annotation.Id) maps to the _id field.

  2. A property or field without an annotation but named id maps to the _id field.

The following outlines what type conversion, if any, is done on the property mapped to the _id document field when using the MappingMongoConverter (the default for MongoTemplate).

  1. If possible, an id property or field declared as a String in the Java class is converted to and stored as an ObjectId by using a Spring Converter<String, ObjectId>. Valid conversion rules are delegated to the MongoDB Java driver. If it cannot be converted to an ObjectId, then the value is stored as a string in the database.

  2. An id property or field declared as BigInteger in the Java class is converted to and stored as an ObjectId by using a Spring Converter<BigInteger, ObjectId>

If no field or property specified in the previous sets of rules is present in the Java class, an implicit _id file is generated by the driver but not mapped to a property or field of the Java class.

When querying and updating, MongoTemplate uses the converter that corresponds to the preceding rules for saving documents so that field names and types used in your queries can match what is in your domain classes.

Some environments require a customized approach to map Id values such as data stored in MongoDB that did not run through the Spring Data mapping layer. Documents can contain _id values that can be represented either as ObjectId or as String. Reading documents from the store back to the domain type works just fine. Querying for documents via their id can be cumbersome due to the implicit ObjectId conversion. Therefore documents cannot be retrieved that way. For those cases @MongoId provides more control over the actual id mapping attempts.

Example 62. @MongoId mapping

public class PlainStringId {
  @MongoId String id; 
}

public class PlainObjectId {
  @MongoId ObjectId id; 
}

public class StringToObjectId {
  @MongoId(FieldType.OBJECT_ID) String id; 
}

The id is treated as String without further conversion.The id is treated as ObjectId.

The id is treated as ObjectId if the given String is a valid ObjectId hex, otherwise as String. Corresponds to @Id usage.

private String id; //spring自定转换为主键_id
private BigInteger id; //spring自定转换为主键_id
@Id //标记为主键_id

若使用id作为自定义字段,非主键_id
可设置@Field注解
@Field("id")
private Long id;