[Spring Data MongoDB] Learning Note--_id and type mapping

Source: Internet
Author: User

Mapping of _id fields:

MongoDB requires that all document have a _id field.

If we don't have an incoming _id field in use, it will create a objectid on its own.

{"_id": ObjectId ("53E0FF0B0364CB4A98CE3BFD"),"_class":"Org.springframework.data.mongodb.examples.hello.domain.Person","name":"John"," Age": the,"accounts": [ {"_id":NULL,"AccountNumber":"1234-59873-893-1","AccountType":"SAVINGS","Balance":123.45} ] }

Mongomappingconverter the Java class to the _id field according to the following rules:

1. @Id org.springframework.data.annotation.Id the field or attribute that is marked ().

2. There is no tag, but the name is the field or attribute of the ID (type is string or BigInteger).

Type mapping

If an object contains another object, it is stored by default in the _class field, for example

 Public class Sample {contact  value;}  Public Abstract class Contact {...}  Public class extends  newnew"_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 following example is pers.

@TypeAlias ("pers")class person {}

Define your own mongotypemapper.

1. Using Java Config

class extends defaultmongotypemapper {  //implement custom type mappinghere}
@ConfigurationclassSamplemongoconfigurationextendsabstractmongoconfiguration {@OverrideprotectedString GetDatabaseName () {return"Database"; } @Override PublicMongo Mongo ()throwsException {return NewMongo (); } @Bean @Override PublicMappingmongoconverter Mappingmongoconverter ()throwsException {mappingmongoconverter mmc=Super. Mappingmongoconverter ();        Mmc.settypemapper (Customtypemapper ()); returnMMC; } @Bean Publicmongotypemapper Customtypemapper () {return NewCustommongotypemapper (); }}

2. Using XML

<type-mapper-ref= "Custommongotypemapper"/><   name= "Custommongotypemapper"  class= "Com.bubu.mongo.CustomMongoTypeMapper"  />

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.