_id字段的映射:
MongoDB要求所有的document都要有一個_id的字段。
如果我們在使用中沒有傳入_id字段,它會自己創建一個ObjectId.
{ "_id" : ObjectId("53e0ff0b0364cb4a98ce3bfd"), "_class" : "org.springframework.data.mongodb.examples.hello.domain.Person", "name" : "John", "age" : 39, "accounts" : [ { "_id" : null, "accountNumber" : "1234-59873-893-1", "accountType" : "SAVINGS", "balance" : 123.45 } ] }
MongoMappingConverter按照下面的規則將java class對應到_id字段:
1. 被標記為@Id
(org.springframework.data.annotation.Id
) 的字段或者屬性。
2. 沒有標記,但是名字是id的字段或者屬性(類型為string或者BigInteger)。
類型映射
如果一個object中包含另一個object,默認存放在_class字段下,例如
public class Sample { Contact value; } public abstract class Contact { … } public class Person extends Contact { … } Sample sample = new Sample(); sample.value = new Person(); mongoTemplate.save(sample); { "_class" : "com.acme.Sample", "value" : { "_class" : "com.acme.Person" } }
通過使用@TypeAlias可以把在_class下面存放的值變成固定的值,下面的例子為pers。
@TypeAlias("pers") class Person { }
定義自己的MongoTypeMapper
1. 使用java config
class CustomMongoTypeMapper extends DefaultMongoTypeMapper { //implement custom type mapping here }
@Configuration class SampleMongoConfiguration extends AbstractMongoConfiguration { @Override protected String getDatabaseName() { return "database"; } @Override public Mongo mongo() throws Exception { return new Mongo(); } @Bean @Override public MappingMongoConverter mappingMongoConverter() throws Exception { MappingMongoConverter mmc = super.mappingMongoConverter(); mmc.setTypeMapper(customTypeMapper()); return mmc; } @Bean public MongoTypeMapper customTypeMapper() { return new CustomMongoTypeMapper(); } }
2. 使用xml
<mongo:mapping-converter type-mapper-ref="customMongoTypeMapper"/> <bean name="customMongoTypeMapper" class="com.bubu.mongo.CustomMongoTypeMapper"/>