[Spring Data MongoDB]學習筆記--_id和類型映射


_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"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM