13.07.2015 Views

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

please define productname in your docbook file!When querying and updating MongoTemplate will use the converter to handle conversions of theQuery and Update objects that correspond to the above rules for saving documents so field namesand types used in your queries will be able to match what is in your domain classes.Type mappingAs <strong>MongoDB</strong> collections can contain documents that represent instances of a variety of types. A greatexample here is if you store a hierarchy of classes or simply have a class with a property of type Object.In the latter case the values held inside that property have to be read in correctly when retrieving theobject. Thus we need a mechanism to store type information alongside the actual document.To achieve that the MappingMongoConverter uses a MongoTypeMapper abstraction withDefaultMongoTypeMapper as it's main implementation. It's default behaviour is storing the fullyqualified classname under _class inside the document for the top-level document as well as for everyvalue if it's a complex type and a subtype of the property type declared.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" }}Example 5.7 Type mappingAs you can see we store the type information for the actual root class persistet as well asfor the nested type as it is complex and a subtype of Contact. So if you're now usingmongoTemplate.findAll(Object.class, "sample") we are able to find out that the documentstored shall be a Sample instance. We are also able to find out that the value property shall be a Personactually.Customizing type mappingIn case you want to avoid writing the entire Java class name as type information but rather like to usesome key you can use the @TypeAlias annotation at the entity class being persisted. If you need tocustomize the mapping even more have a look at the TypeInformationMapper interface. An instanceof that interface can be configured at the DefaultMongoTypeMapper which can be configured in turnon MappingMongoConverter.@TypeAlias("pers")class Person {}Note that the resulting document will contain "pers" as the value in the _class Field.Example 5.8 Defining a TypeAlias for an Entity1.4.0.BUILD-SNAPSHOT<strong>Spring</strong> <strong>Data</strong> <strong>MongoDB</strong> -Reference Documentation 39

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!