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!NoteThe preferred way to reference the operations on MongoTemplate instance is via its interfaceMongoOperations.The default converter implementation used by MongoTemplate is MongoMappingConverter. While theMongoMappingConverter can make use of additional metadata to specify the mapping of objects todocuments it is also capable of converting objects that contain no additonal metadata by using someconventions for the mapping of IDs and collection names. These conventions as well as the use ofmapping annotations is explained in the Mapping chapter.NoteIn the M2 release SimpleMappingConverter, was the default and this class is now deprecatedas its functionality has been subsumed by the MongoMappingConverter.Another central feature of MongoTemplate is exception translation of exceptions thrown in the <strong>MongoDB</strong>Java driver into <strong>Spring</strong>'s portable <strong>Data</strong> Access Exception hierarchy. Refer to the section on exceptiontranslation for more information.While there are many convenience methods on MongoTemplate to help you easily perform commontasks if you should need to access the <strong>MongoDB</strong> driver API directly to access functionality notexplicitly exposed by the MongoTemplate you can use one of several Execute callback methodsto access underlying driver APIs. The execute callbacks will give you a reference to either acom.mongodb.Collection or a com.mongodb.DB object. Please see the section ExecutionCallbacks for more information.Now let's look at a examples of how to work with the MongoTemplate in the context of the <strong>Spring</strong>container.Instantiating MongoTemplateYou can use Java to create and register an instance of MongoTemplate as shown below.@Configurationpublic class AppConfig {public @Bean Mongo mongo() throws Exception {return new Mongo("localhost");}}public @Bean MongoTemplate mongoTemplate() throws Exception {return new MongoTemplate(mongo(), "mydatabase");}Example 5.6 Registering a com.mongodb.Mongo object and enabling <strong>Spring</strong>'s exception translationsupportThere are several overloaded constructors of MongoTemplate. These are• MongoTemplate (Mongo mongo, String databaseName) - takes the com.mongodb.Mongoobject and the default database name to operate against.1.4.0.BUILD-SNAPSHOT<strong>Spring</strong> <strong>Data</strong> <strong>MongoDB</strong> -Reference Documentation 34

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

Saved successfully!

Ooh no, something went wrong!