From f2305681d3b33081a429cf1e5e84403df7214917 Mon Sep 17 00:00:00 2001 From: Mark Pollack Date: Wed, 25 May 2011 00:30:10 -0400 Subject: [PATCH] DATADOC-147 - Update reference documentation to cover changes from M2 to M3 (partial work) --- .../data/document/mongodb/MongoTemplate.java | 6 +- src/docbkx/introduction/introduction.xml | 2 +- src/docbkx/reference/mongodb.xml | 743 +++++++++--------- 3 files changed, 391 insertions(+), 360 deletions(-) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java index 013f60e60..879a99a9b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java @@ -819,14 +819,14 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware { } final DBObject queryObject = query.getQueryObject(); final MongoPersistentEntity entity = getPersistentEntity(targetClass); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("remove using query: " + queryObject + " in collection: " + collectionName); - } execute(collectionName, new CollectionCallback() { public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException { DBObject dboq = mapper.getMappedObject(queryObject, entity); WriteResult wr = null; WriteConcern writeConcernToUse = prepareWriteConcern(writeConcern); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("remove using query: " + queryObject + " in collection: " + collection.getName()); + } if (writeConcernToUse == null) { wr = collection.remove(dboq); } else { diff --git a/src/docbkx/introduction/introduction.xml b/src/docbkx/introduction/introduction.xml index 90979cc3e..fb3c51d73 100644 --- a/src/docbkx/introduction/introduction.xml +++ b/src/docbkx/introduction/introduction.xml @@ -17,7 +17,7 @@ url="http://static.springframework.org/spring/docs/3.0.x/reference/beans.html">IoC container, type - conversion system, , expression language, JMX diff --git a/src/docbkx/reference/mongodb.xml b/src/docbkx/reference/mongodb.xml index 0e6742eb9..ae6858c1a 100644 --- a/src/docbkx/reference/mongodb.xml +++ b/src/docbkx/reference/mongodb.xml @@ -638,9 +638,10 @@ public class MongoConfiguration { The class MongoTemplate, located in the package org.springframework.data.document.mongodb, is the central class of the Spring's MongoDB support providng a rich feature - set. The template offers convenience operations to create, update, delete - and query for MongoDB document and provide a mapping between your domain - objects and MongoDB documents. + set to interact with the database. The template offers convenience + operations to create, update, delete and query for MongoDB documents and + provides a mapping between your domain objects and MongoDB + documents. Once configured, MongoTemplate is @@ -659,16 +660,18 @@ public class MongoConfiguration { interface MongoOperations. In as much as possible, the methods on MongoOperations are named after methods available on the MongoDB driver - Collection object. For example, you will find - methods such as "find", "findAndModify", "findOne", "insert", "remove", - "save", "update" and "updateMulti". The design goal was to make it as easy - as possible to transition between the use of the base MongoDB driver and - MongoOperations. The difference in betwee - the two is that MongOperations can be passed domain objects instead of - DBObject and there are fluent APIs for - Query, Criteria, and - Update operations instead of - DBObject.. + Collection object as as to make the API familiar to + existing MongoDB developers who are used to the driver API. For example, + you will find methods such as "find", "findAndModify", "findOne", + "insert", "remove", "save", "update" and "updateMulti". The design goal + was to make it as easy as possible to transition between the use of the + base MongoDB driver and MongoOperations. A + major difference in between the two APIs is that MongOperations can be + passed domain objects instead of DBObject and there + are fluent APIs for Query, + Criteria, and Update + operations instead of populating a DBObject to + specify the parameters for those operatiosn. The preferred way to reference the operations on @@ -677,14 +680,17 @@ public class MongoConfiguration { The default converter implementation used by - MongoTemplate is - SimpleMappingConverter, which as the name implies, - is simple. SimpleMapingConverter does not use any - additional mapping metadata to converter a domain object to a MongoDB - document. As such, it does not support functionality such as DBRefs or - creating indexes using annotations on domain classes. For a detailed - description of the MongoMappingConverter read the section on Mapping Support. + MongoTemplate is MongoMappingConverter. While the + MongoMappingConverter can make use of additional + metadata to specify the mapping of objects to documents it is also capable + of converting objects that contain no additonal metadata by using some + conventions for the mapping of IDs and collection names. These conventions + as well as the use of mapping annotations is explained in the Mapping chapter. + In the M2 release SimpleMappingConverter, + was the default and this class is now deprecated as its functionality + has been subsumed by the MongoMappingConverter. + Another central feature of MongoTemplate is exception translation of exceptions thrown in the Mongo Java driver into Spring's portable Data @@ -696,9 +702,11 @@ public class MongoConfiguration { MongoTemplate to help you easily perform common tasks if you should need to access the Mongo driver API directly to access functionality not explicitly exposed by the MongoTemplate you can use one - of several Execute callback methods. These will give you a reference to a - Mongo Collection or DB object. Please see the section Execution Callbacks for more + of several Execute callback methods to access underlying driver APIs. The + execute callbacks will give you a reference to either a + com.mongodb.Collection or a + com.mongodb.DB object. Please see the section + Execution Callbacks for more information. Now let's look at a examples of how to work with the @@ -723,7 +731,7 @@ public class AppConfig { } public @Bean MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "mydatabase", "mycollection"); + return new MongoTemplate(mongo(), "mydatabase"); } } @@ -735,23 +743,30 @@ public class AppConfig { MongoTemplate - (Mongo mongo, String databaseName) - takes the - default database name to operate against + (Mongo mongo, String databaseName) - takes the + com.mongodb.Mongo object and the default database name to operate + against. MongoTemplate - (Mongo mongo, String databaseName, String - defaultCollectionName) - adds the default collection name - to operate against. + (Mongo mongo, String databaseName, UserCredentials + userCredentials) - adds the username and password for + authenticating with the database. + + + + MongoTemplate + (MongoDbFactory mongoDbFactory) - takes a + MongoDbFactory object that encapsulated the com.mongodb.Mongo + object, database name, and username and password. MongoTemplate - (Mongo mongo, String databaseName, String - defaultCollectionName, MongoConverter mongoConverter) - - override with a provided MongoConverter. Default is - SimpleMongoConverter + (MongoDbFactory mongoDbFactory, MongoConverter + mongoConverter) - adds a MongoConverter to use for + mapping. @@ -763,12 +778,13 @@ public class AppConfig { <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="geospatial"/> - <constructor-arg name="defaultCollectionName" value="newyork"/> </bean> - Other properties that you might like to set when creating a - MongTemplate are WriteResultCheckingPolicy and the default - WriteConcern. + Other optional properties that you might like to set when creating + a MongoTemplate are the default + WriteResultCheckingPolicy, + WriteConcern, and SlaveOk + write option. The preferred way to reference the operations on @@ -780,43 +796,37 @@ public class AppConfig { WriteResultChecking Policy When in development it is very handy to either log or throw an - exception if the WriteResult returned from any MongoDB operation - contains an error. It is quite common to forget to do this during - development and then end up with an application that looks like it ran - successfully but the database was not modified according to your - expectations. Setting the WriteResultChecking is an enum with the - following values, NONE, LOG, EXCEPTION. - - The default is to use a WriteResultChecking of NONE. + exception if the com.mongodb.WriteResult + returned from any MongoDB operation contains an error. It is quite + common to forget to do this during development and then end up with an + application that looks like it runs successfully but in fact the + database was not modified according to your expectations. Set + MongoTemplate's WriteResultChecking property to + an enum with the following values, LOG, EXCEPTION, or NONE to either + log the error, throw and exception or do nothing. The default is to + use a WriteResultChecking value of NONE.
WriteConcern - You can set the WriteConcern property that the MongoTemplate - will use for write operations if it has not yet been specifid with the - driver. If not set, it will default to the one set in the MongoDB - driver's DB or Collection setting. + You can set the com.mongodb.WriteConcern + property that the MongoTemplate will use for + write operations if it has not yet been specified via the driver at a + higher level such as com.mongodb.Mongo. If MongoTemplate's + WriteConcern property is not set it will + default to the one set in the MongoDB driver's DB or Collection + setting. - Setting the WriteConcern to different values when saving an - object will be provided in a future release. This will most likely - be handled using mapping metadata provided either in the form of - annotations on the domain object or by an external fluent - DSL. + Setting the WriteConcern to different + values when saving an object will be provided in a future release. + This will most likely be handled using mapping metadata provided + either in the form of annotations on the domain object or by an + external fluent DSL.
- -
- Configuring the MongoConverter - - The SimpleMongoConverter is used by default but if you want to use - the more feature rich MappingMongoConverter there are a few steps. - Please refer to the mapping section for more - information. -
@@ -831,12 +841,31 @@ public class AppConfig { public class Person { private String id; - private String firstName; + private String name; private int age; - - // getters and setter omitted - -} + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getId() { + return id; + } + public String getName() { + return name; + } + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Person [id=" + id + ", name=" + name + ", age=" + age + "]"; + } + +} + You can save, update and delete the object as shown below. @@ -845,51 +874,72 @@ public class AppConfig { that MongoTemplate implements. - public class PersonExample { + package org.spring.example; - private static final Log log = LogFactory.getLog(PersonExample.class); - - @Autowired - private MongoOperations mongoOps; - - public void doWork() { - - Person p = new Person(); - p.setFirstName("Sven"); - p.setAge(22); +import static org.springframework.data.document.mongodb.query.Criteria.where; +import static org.springframework.data.document.mongodb.query.Update.update; +import static org.springframework.data.document.mongodb.query.Query.query; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.data.document.mongodb.MongoOperations; +import org.springframework.data.document.mongodb.MongoTemplate; +import org.springframework.data.document.mongodb.SimpleMongoDbFactory; + +import com.mongodb.Mongo; + +public class MongoApp { + + private static final Log log = LogFactory.getLog(MongoApp.class); + + public static void main(String[] args) throws Exception { + + MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database")); + + Person p = new Person("Joe", 34); - // Save - mongoOps.save(p); - log.debug("Saved: " + p); + // Insert is used to initially store the object into the database. + mongoOps.insert(p); + log.info("Insert: " + p); // Find - p = mongoOps.findOne(query(whereId().is(p.getId())), Person.class); - log.debug("Found: " + p); + p = mongoOps.findById(p.getId(), Person.class); + log.info("Found: " + p); - // Update age to 24 for Sven - mongoOps.updateFirst(query(where("firstName").is("Sven")), update("age", 24)); - p = mongoOps.findOne(query(whereId().is(p.getId())), Person.class); - log.debug("Updated: " + p); + // Update + mongoOps.updateFirst(Person.class, query(where("name").is("Joe")), update("age", 35)); + p = mongoOps.findOne(query(where("name").is("Joe")), Person.class); + log.info("Updated: " + p); - // Delete + // Delete mongoOps.remove(p); - + // Check that deletion worked List<Person> people = mongoOps.getCollection(Person.class); - log.debug("Number of people = : " + people.size()); + log.info("Number of people = : " + people.size()); -} + + mongoOps.dropCollection("person"); + } +} + - This would produce the following log output (including some debug - message from MongoTemplate itself) + This would produce the following log output (including debug + messages from MongoTemplate itself) - Saved: PersonWithIdPropertyOfTypeString [id=4d9e82ac94fa72c65a9e7d5f, firstName=Sven, age=22] -findOne using query: { "_id" : { "$oid" : "4d9e82ac94fa72c65a9e7d5f"}} in db.collection: database.personexample -Found: PersonWithIdPropertyOfTypeString [id=4d9e82ac94fa72c65a9e7d5f, firstName=Sven, age=22] -findOne using query: { "_id" : { "$oid" : "4d9e82ac94fa72c65a9e7d5f"}} in db.collection: database.personexample -Updated: PersonWithIdPropertyOfTypeString [id=4d9e82ac94fa72c65a9e7d5f, firstName=Sven, age=24] -remove using query: { "_id" : { "$oid" : "4d9e82ac94fa72c65a9e7d5f"}} -Number of people = : 0 + DEBUG apping.MongoPersistentEntityIndexCreator: 80 - Analyzing class class org.spring.example.Person for index information. +DEBUG work.data.document.mongodb.MongoTemplate: 632 - insert DBObject containing fields: [_class, age, name] in collection: Person +INFO org.spring.example.MongoApp: 30 - Insert: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34] +DEBUG work.data.document.mongodb.MongoTemplate:1246 - findOne using query: { "_id" : { "$oid" : "4ddc6e784ce5b1eba3ceaf5c"}} in db.collection: database.Person +INFO org.spring.example.MongoApp: 34 - Found: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34] +DEBUG work.data.document.mongodb.MongoTemplate: 778 - calling update using query: { "name" : "Joe"} and update: { "$set" : { "age" : 35}} in collection: Person +DEBUG work.data.document.mongodb.MongoTemplate:1246 - findOne using query: { "name" : "Joe"} in db.collection: database.Person +INFO org.spring.example.MongoApp: 39 - Updated: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=35] +DEBUG work.data.document.mongodb.MongoTemplate: 823 - remove using query: { "id" : "4ddc6e784ce5b1eba3ceaf5c"} in collection: Person +INFO org.spring.example.MongoApp: 46 - Number of people = : 0 +DEBUG work.data.document.mongodb.MongoTemplate: 376 - Dropped collection [database.person] There was implicit conversion using the MongoConverter between a String and ObjectId as stored in the database and recognizing a convention @@ -914,7 +964,7 @@ Number of people = : 0 mapped to this '_id' field. The following outlines what property will be mapped to the '_id' - field: + document field: @@ -925,31 +975,39 @@ Number of people = : 0 - A property or field named id will be - mapped to the '_id' field. - - - - A property or field declared as a String in the Java class - will be converted to and stored as an ObjectId if possible - (conversions and rules would be handled by the Mongo Java driver). - If it cannot be converted to an ObjectId, then the value will be - stored as a string in the database. - - - - A property or field declared as anything but a String in the - Java class will be stored as the type it is declared as, which - means it must be one of the basic types supported by the Mongo - Java driver. + A property or field without an annotation but named + id will be mapped to the '_id' + field. + The following outlines what type conversion, if any, will be done + on the property mapped to the _id document field when using the + MappingMongoConverter, the default for + MongoTemplate. + + + + An id property or field declared as a String in the Java class + will be converted to and stored as an ObjectId if possible using a + Spring Converter<String, ObjectId>. Valid conversion rules are + delegated to the Mongo Java driver. If it cannot be converted to an + ObjectId, then the value will be stored as a string in the + database. + + + + An id property or field declared as BigInteger in the Java + class will be converted to and stored as an ObjectId using a Spring + Converter<BigInteger, ObjectId>. + + + If no field or property specified above is present in the Java class then an implicit '_id' file will be generated by the driver but not mapped to a property or field of the Java class. - When querying and updating the JdbcTemplate + When querying and updating MongoTemplate will use the converter to handle conversions of the Query and Update objects that correspond to the above rules for saving documents so field names @@ -960,12 +1018,12 @@ Number of people = : 0
Methods for saving and inserting documents - There are several convenient methods on MongoTemplate for saving - and inserting your objects. In addition to using a - MongoCoverter to converter your domain - object to the database, you can also use an implementation of the - MongoWriter interface to have very fine - grained control over the conversion process. + There are several convenient methods on + MongoTemplate for saving and inserting your + objects. To have more fine grained control over the conversion process + you can register Spring converters with the MappingMongoConverter, for + example Converter<Person, DBObject> and Converter<DBObject, + Person>. The difference between insert and save operations is that a save @@ -973,11 +1031,11 @@ Number of people = : 0 present. - The simple case of using the save operation is to pass in as an - argument only the object to save. In this case the default collection - assigned to the template will be used unless the converter overrides - this default through the use of more specific mapping metadata. You may - also call the save operation with a specific collection name. + The simple case of using the save operation is to save a POJO. In + this case the collection name will be determined by name (not fully + qualfied) of the class. You may also call the save operation with a + specific collection name. The collection to store the object can be + overriden using mapping metadata. When inserting or saving, if the Id property is not set, the assumption is that its value will be autogenerated by the database. As @@ -1019,20 +1077,6 @@ import static org.springframework.data.document.mongodb.query.Criteria.query; (String collectionName, Object objectToSave) Save the object to the specified collection. - - - <T> void save - (T objectToSave, MongoWriter<T> writer) - Save the object into the default collection using the - provided writer. - - - - <T> void save - (String collectionName, T objectToSave, - MongoWriter<T> writer) Save the object into the - specified collection using the provided writer. - A similar set of insert operations is listed below @@ -1049,52 +1093,8 @@ import static org.springframework.data.document.mongodb.query.Criteria.query; (String collectionName, Object objectToSave) Insert the object to the specified collection. - - - <T> void insert (T objectToSave, - MongoWriter<T> writer) Insert the object into the - default collection using the provided writer. - - - - <T> void insert (String collectionName, T - objectToSave, MongoWriter<T> writer) Insert the - object into the specified collection using the provided - writer. - - Unless and explicit MongoWriter is passed into the save or insert - method, the the template's MongoConverter will be used. - -
- Saving using MongoWriter - - The MongoWriter interface allows you to have lower level control - over the mapping of an object into a DBObject. The MongoWriter - interface is - - /** - * A MongoWriter is responsible for converting an object of type T to the native MongoDB - * representation DBObject. - * - * @param <T> the type of the object to convert to a DBObject - */ -public interface MongoWriter<T> { - - /** - * Write the given object of type T to the native MongoDB object representation DBObject. - * - * @param t The object to convert to a DBObject - * @param dbo The DBObject to use for writing. - */ - void write(T t, DBObject dbo); - -} -
-
Inserting Lists of objects in batch @@ -1119,23 +1119,6 @@ public interface MongoWriter<T> { objects into the specified collection in a single batch write to the database. - - - <T> void insertList (List<? extends - T> listToSave, MongoWriter<T> writer) - Insert the object into the default - collection using the provided writer. - - - - <T> void insertList(String - collectionName, List<? extends T> listToSave, - MongoWriter<T> writer) Insert a list of objects - into the specified collection using the provided MongoWriter - instance -
@@ -1155,13 +1138,13 @@ public interface MongoWriter<T> { Updating documents using the MongoTemplate import static org.springframework.data.document.mongodb.query.Criteria.where; -import static org.springframework.data.document.mongodb.query.Query.query; -import static org.springframework.data.document.mongodb.query.Update +import static org.springframework.data.document.mongodb.query.Query; +import static org.springframework.data.document.mongodb.query.Update; ... - WriteResult wr = mongoTemplate.updateMulti(query(where("accounts.accountType").is(Account.Type.SAVINGS)), - update.inc("accounts.$.balance", 50.00)); + WriteResult wr = mongoTemplate.updateMulti(Account.class, new Query(where("accounts.accountType").is(Account.Type.SAVINGS)), + new Update().inc("accounts.$.balance", 50.00)); @@ -1180,10 +1163,11 @@ import static org.springframework.data.document.mongodb.query.Update WriteResult updateFirst (Query query, - Update update) Updates the first object that is found - in the default collection that matches the query document with - the provided updated document. + role="bold">updateFirst (Class class, Query + query, Update update) Updates the first object that + is found in the collection corresponding to the class that + matches the query document with the provided updated + document. @@ -1197,10 +1181,11 @@ import static org.springframework.data.document.mongodb.query.Update WriteResult updateMulti (Query query, - Update update) Updates all objects that are found in - the default collection that matches the query document criteria - with the provided updated document. + role="bold">updateMulti (Class class, Query + query, Update update) Updates all objects that are + found in the collection corresponding to the class that matches + the query document criteria with the provided updated + document.
@@ -1219,6 +1204,14 @@ import static org.springframework.data.document.mongodb.query.Update
Methods for the Update class + The Update class can be used with a little 'syntax sugar' as its + methods are meant to be chained together and you can kickstart the + creation of a new Update instance via the static method + public static Update update(String key, Object + value) and using static imports. + + Here is a listing of methods on the Update class + Update addToSet @@ -1285,8 +1278,6 @@ import static org.springframework.data.document.mongodb.query.Update $unset update modifier - -
@@ -1330,7 +1321,7 @@ import static org.springframework.data.document.mongodb.query.Update role="bold">remove (String collectionName, Query query, Class<T> targetClass)Same behavior as remove(Query, Class) but the Class parameter is used to help - convert the Id of the object if it is present in the uqery + convert the Id of the object if it is present in the query @@ -1341,13 +1332,16 @@ import static org.springframework.data.document.mongodb.query.Update
Querying Documents - You can express you queries using the Query and Criteria classes - which have method names that mirror the native MongoDB operator names such - as lt, lte, is, and others. The Query and Criteria classes follow a fluent - API style so that you can easily chain together multiple method criteria - and queries while having easy to understand code. Static imports in Java - are used to help remove the need to see the 'new' keyword for creating - Query and Criteria instances so as to improve readability. + You can express your queries using the Query + and Criteria classes which have method names that + mirror the native MongoDB operator names such as lt, + lte, is, and others. The + Query and Criteria classes + follow a fluent API style so that you can easily chain together multiple + method criteria and queries while having easy to understand code. Static + imports in Java are used to help remove the need to see the 'new' keyword + for creating Query and Criteria instances so as to improve + readability. GeoSpatial queries are also supported and are described more in the section GeoSpatial Queries. @@ -1355,12 +1349,13 @@ import static org.springframework.data.document.mongodb.query.Update
Querying documents in a collection - We saw how to retrieve a single document. We can also query for a - collection of documents to be returned as domain objects in a list. - Assuming that we have a number of Person objects with name and age - stored as documents in a collection and that each person has an embedded - account document with a balance. We can now run a query using the - following code. + We saw how to retrieve a single document using the findOne and + findById methods on MongoTemplate in previous sections which return a + single domain object. We can also query for a collection of documents to + be returned as a list of domain objects. Assuming that we have a number + of Person objects with name and age stored as documents in a collection + and that each person has an embedded account document with a balance. We + can now run a query using the following code. Querying for documents using the MongoTemplate @@ -1404,6 +1399,15 @@ import static org.springframework.data.document.mongodb.query.Query.query; using the $all operator + + Criteria and + (String key) Adds a chained + Criteria with the specified + key to the current + Criteria and retuns the newly created + one + + Criteria elemMatch (Criteria c) @@ -1432,7 +1436,15 @@ import static org.springframework.data.document.mongodb.query.Query.query; Criteria in (Object... o) Creates a criterion - using the $in operator + using the $in operator for a varargs + argument. + + + + Criteria in + (Collection<?> collection) + Creates a criterion using the $in + operator using a collection @@ -1460,6 +1472,12 @@ import static org.springframework.data.document.mongodb.query.Query.query; $mod operator + + Criteria ne + (Object o)Creates a criterion + using the $ne operator + + Criteria nin (Object... o) Creates a criterion @@ -1473,6 +1491,14 @@ import static org.springframework.data.document.mongodb.query.Query.query; directly following + + Criteria or + (List<Query> + queries)Creates an or query using the + $or operator for all of the provided + queries + + Criteria regex (String re) Creates a criterion @@ -1490,15 +1516,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; (int t)Creates a criterion using the $type operator - - - Criteria and - (String key) Adds a chained - Criteria with the specified - key to the current - Criteria and retuns the newly created - one -
@@ -1542,6 +1559,13 @@ import static org.springframework.data.document.mongodb.query.Query.query; criterion using $nearSphere$center operations. This is only available for Mongo 1.7 and higher. + + + Criteria maxDistance + (double maxDistance) Creates a + geospatial criterion using the $maxDistance + operation, for use with $near. + The Query class has some additional methods @@ -1590,8 +1614,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; Sort sort () used to provide sort definition for the results - - @@ -1616,15 +1638,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; list of objects of type T from the specified collection. - - <T> List<T> getCollection (String - collectionName, Class<T> targetClass, MongoReader<T> - reader) Query for a list of objects of type T from the - specified collection, mapping the DBObject using the provided - MongoReader. - - <T> T findOne (Query query, Class<T> targetClass) @@ -1633,14 +1646,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; specified type. - - <T> T findOne - (Query query, Class<T> targetClass, - MongoReader<T> reader) Map the results of an - ad-hoc query on the default MongoDB collection to a single - instance of an object of the specified type. - - <T> T findOne (String collectionName, Query query, @@ -1650,12 +1655,17 @@ import static org.springframework.data.document.mongodb.query.Query.query; - <T> T findOne - (String collectionName, Query query, - Class<T> targetClass, MongoReader<T> reader) - Map the results of an ad-hoc query on the specified - collection to a single instance of an object of the specified - type. + <T> T findById (Object id, + Class<T> targetClass) Return an object of the + given id and target class. + + + + <T> T findById (String collectionName, + Object id,Class<T> targetClass) Return an object + in the collection for a given id and target class. @@ -1665,14 +1675,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; default MongoDB collection to a List of the specified type. - - <T> List<T> find (Query query, Class<T> - targetClass, MongoReader<T> reader) Map the - results of an ad-hoc query on the default MongoDB collection to a - List of the specified type. - - <T> List<T> find (String collectionName, @@ -1689,14 +1691,6 @@ import static org.springframework.data.document.mongodb.query.Query.query; collection to a List of the specified type. - - <T> List<T> find (String collectionName, - Query query, Class<T> targetClass, MongoReader<T> - reader) Map the results of an ad-hoc query on the - specified collection to a List of the specified type. - - <T> T findAndRemove (Query query, @@ -1727,53 +1721,7 @@ import static org.springframework.data.document.mongodb.query.Query.query; type. The first document that matches the query is returned and also removed from the collection in the database. - - - <T> T findAndRemove (String - collectionName, Query query, Class<T> targetClass, - MongoReader<T> reader) Map the results of an - ad-hoc query on the specified collection to a single instance of - an object of the specified type. The first document that matches - the query is returned and also removed from the collection in the - database. - - - The MongoReader can be used - -
- Reading using MongoWriter - - The MongoReader interface allows you to have lower level control - over the mapping of an DBObject into a Java object. This is similar to - the role of RowMapper in JdbcTemplate. The MongoReader interface - is - - /** - * A MongoWriter is responsible for converting a native MongoDB DBObject to an object of type T. - * - * @param <T> the type of the object to convert from a DBObject - */ -public interface MongoReader<T> { - - /** - * Ready from the native MongoDB DBObject representation to an instance of the class T. - * The given type has to be the starting point for marshalling the {@link DBObject} - * into it. So in case there's no real valid data inside {@link DBObject} for the - * given type, just return an empty instance of the given type. - * - * @param clazz the type of the return value - * @param dbo theDBObject - * @return the converted object - */ - <S extends T> S read(Class<S> clazz, DBObject dbo); -} - - - - -
@@ -1872,6 +1820,99 @@ List<Venue> venues =
+
+ Overriding default mapping with custom converters + + In order to have more fine grained control over the mapping process + you can register Spring converters with the + MongoConverter implementations such as the + MappingMongoConverter. + + The MappingMongoConverter checks to see if + there are any Spring converters that can handle a specific class before + attempting to map the object itself. To 'hijack' the normal mapping + strategies of the MappingMongoConverter, perhaps for increased performance + or other custom mapping needs, you first need to create an implementation + of the Spring Converter interface and then + register it with the MappingConverter. + + + For more information on the Spring type conversion service see the + reference docs here. + + +
+ Saving using a registered Spring Converter + + An example implementation of the + Converter that converts from a Person + object to a com.mongodb.DBObject is shown + below + + import org.springframework.core.convert.converter.Converter; + +import com.mongodb.BasicDBObject; +import com.mongodb.DBObject; + +public class PersonWriteConverter implements Converter<Person, DBObject> { + + public DBObject convert(Person source) { + DBObject dbo = new BasicDBObject(); + dbo.put("_id", source.getId()); + dbo.put("name", source.getFirstName()); + dbo.put("age", source.getAge()); + return dbo; + } + +} +
+ +
+ Reading using a Spring Converter + + An example implemention of a Converter that converts from a + DBObject ot a Person object is shownn below + + public class PersonReadConverter implements Converter<DBObject, Person> { + + public Person convert(DBObject source) { + Person p = new Person((ObjectId) source.get("_id"), (String) source.get("name")); + p.setAge((Integer) source.get("age")); + return p; + } + +} +
+ +
+ Registering Spring Converters with the MongoConverter + + The mongo XSD namespace provides a convenience way to register + Spring Converters as shown below as well as configuring it into a + MongoTemplate. + + <mongo:db-factory dbname="database"/> + +<mongo:mapping-converter> + <mongo:custom-converters> + <mongo:converter ref="readConverter"/> + <mongo:converter> + <bean class="org.springframework.data.document.mongodb.PersonWriteConverter"/> + </mongo:converter> + </mongo:custom-converters> +</mongo:mapping-converter> + +<bean id="readConverter" class="org.springframework.data.document.mongodb.PersonReadConverter"/> + +<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> + <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> + <constructor-arg name="mongoConverter" ref="mappingConverter"/> +</bean> + +
+
+
Index and Collection managment @@ -1973,22 +2014,7 @@ mongoTemplate.dropCollection("MyNewCollection"); collectionName) Get a collection by name, creating it if it doesn't exist. - - - DBCollection getDefaultCollection () - The default collection used by this template. - - - - String getDefaultCollectionName - () The default collection name used by this - template. - - -
@@ -2017,8 +2043,6 @@ mongoTemplate.dropCollection("MyNewCollection"); a JSON string. - - @@ -2159,17 +2183,17 @@ public class BeforeSaveListener<BeforeSaveEvent, Person> extends AbstractM <T> T execute - (CollectionCallback<T> action) - Executes the given CollectionCallback on the default - collection. + (Class<?> entityClass, + CollectionCallback<T> action) Executes the given + CollectionCallback for the entitye collection of the specified + class. <T> T execute (String collectionName, CollectionCallback<T> action) Executes the given - CollectionCallback on the collection of the given name.update using - the $addToSet update modifier + CollectionCallback on the collection of the given name. @@ -2179,6 +2203,13 @@ public class BeforeSaveListener<BeforeSaveEvent, Person> extends AbstractM necessary. + + <T> T execute + (String collectionName, DbCallback<T> + action) Executes a DbCallback on the collection of the + given name translating any exceptions as necessary. + + <T> T executeInSession @@ -2193,7 +2224,7 @@ public class BeforeSaveListener<BeforeSaveEvent, Person> extends AbstractM information about an index. boolean hasIndex = template.execute("geolocation", new CollectionCallback<Boolean>() { - public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException { + public Boolean doInCollection(Venue.class, DBCollection collection) throws MongoException, DataAccessException { List<DBObject> indexes = collection.getIndexInfo(); for (DBObject dbo : indexes) { if ("location_2d".equals(dbo.get("name"))) {