[Spring Data MongoDB] learning notes -- _ id and type ing, mongodb -- _ id
_ Id field ing:
MongoDB requires that all documents have a _ id field.
If the _ id field is not passed in, it will create an 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 maps java class to the _ id field according to the following rules:
1. Marked@Id(org.springframework.data.annotation.Id.
2. There is no flag, but the name is the id field or attribute (type: string or BigInteger ).
Type ing
If an object contains another object, it is stored in the _ class field by default. For example:
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" }}
By using @ TypeAlias, you can change the value stored under _ class to a fixed value. The example below is pers.
@TypeAlias("pers")class Person {}
Define your own deployment typemapper
1. Use java config
class CustomMongoTypeMapper extends DefaultMongoTypeMapper { //implement custom type mapping here}
@Configurationclass 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. Use xml
<mongo:mapping-converter type-mapper-ref="customMongoTypeMapper"/><bean name="customMongoTypeMapper" class="com.bubu.mongo.CustomMongoTypeMapper"/>
Teach Spring Data Mongodb auto-incremental ID implementation
You have to find a place to find the current number of IDs, and then query each insert operation, and add after insert.
Which jar package does orgspringframeworkdatadocumentmongodbworkflow template belong?
This is a mongoDB package. You can go to the next one on the official website. The addresses of the latest template in M2 and M4 versions are different. You can try it yourself.