Browse Source

DATAMONGO-1176 - Cleanup.

Replace DbObject in documentation with Document. Fix typos. Change dbObject variable names to document. Improve error messages. Remove unused code.
pull/411/merge
Mark Paluch 9 years ago committed by Oliver Gierke
parent
commit
59573b10e6
  1. 8
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java
  2. 3
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationFunctionExpressions.java
  3. 27
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ConditionalOperator.java
  4. 10
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/IfNullOperator.java
  5. 3
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefResolver.java
  6. 4
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java
  7. 2
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java
  8. 44
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java
  9. 0
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentPropertyAccessor.java
  10. 35
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java
  11. 24
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverters.java
  12. 15
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java
  13. 23
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java
  14. 4
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Field.java
  15. 4
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbSerializer.java
  16. 26
      spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java
  17. 4
      spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/NamedMongoScriptConvertsUnitTests.java
  18. 32
      src/main/asciidoc/reference/mapping.adoc
  19. 77
      src/main/asciidoc/reference/mongodb.adoc

8
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

@ -654,13 +654,13 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware { @@ -654,13 +654,13 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
}
String collection = StringUtils.hasText(collectionName) ? collectionName : determineCollectionName(entityClass);
Document nearDbObject = near.toDocument();
Document nearDocument = near.toDocument();
Document command = new Document("geoNear", collection);
command.putAll(nearDbObject);
command.putAll(nearDocument);
if (nearDbObject.containsKey("query")) {
Document query = (Document) nearDbObject.get("query");
if (nearDocument.containsKey("query")) {
Document query = (Document) nearDocument.get("query");
command.put("query", queryMapper.getMappedObject(query, getPersistentEntity(entityClass)));
}

3
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationFunctionExpressions.java

@ -28,6 +28,7 @@ import org.springframework.util.Assert; @@ -28,6 +28,7 @@ import org.springframework.util.Assert;
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.7
*/
public enum AggregationFunctionExpressions {
@ -75,7 +76,7 @@ public enum AggregationFunctionExpressions { @@ -75,7 +76,7 @@ public enum AggregationFunctionExpressions {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.Expression#toDbObject(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
* @see org.springframework.data.mongodb.core.aggregation.Expression#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {

27
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ConditionalOperator.java

@ -24,12 +24,9 @@ import org.springframework.data.mongodb.core.query.CriteriaDefinition; @@ -24,12 +24,9 @@ import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Encapsulates the aggregation framework {@code $cond} operator. A {@link ConditionalOperator} allows nested conditions
* {@code if-then[if-then-else]-else} using {@link Field}, {@link CriteriaDefinition} or a {@link DBObject custom}
* {@code if-then[if-then-else]-else} using {@link Field}, {@link CriteriaDefinition} or a {@link Document custom}
* condition. Replacement values can be either {@link Field field references}, values of simple MongoDB types or values
* that can be converted to a simple MongoDB type.
*
@ -68,7 +65,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -68,7 +65,7 @@ public class ConditionalOperator implements AggregationExpression {
}
/**
* Creates a new {@link ConditionalOperator} for a given {@link DBObject criteria} and {@code then}/{@code otherwise}
* Creates a new {@link ConditionalOperator} for a given {@link Document criteria} and {@code then}/{@code otherwise}
* values.
*
* @param condition must not be {@literal null}.
@ -96,7 +93,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -96,7 +93,7 @@ public class ConditionalOperator implements AggregationExpression {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationExpression#toDbObject(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
* @see org.springframework.data.mongodb.core.aggregation.AggregationExpression#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {
@ -112,7 +109,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -112,7 +109,7 @@ public class ConditionalOperator implements AggregationExpression {
private Object resolveValue(AggregationOperationContext context, Object value) {
if (value instanceof DBObject || value instanceof Field) {
if (value instanceof Document || value instanceof Field) {
return resolve(context, value);
}
@ -125,7 +122,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -125,7 +122,7 @@ public class ConditionalOperator implements AggregationExpression {
private Object resolveCriteria(AggregationOperationContext context, Object value) {
if (value instanceof DBObject || value instanceof Field) {
if (value instanceof Document || value instanceof Field) {
return resolve(context, value);
}
@ -144,7 +141,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -144,7 +141,7 @@ public class ConditionalOperator implements AggregationExpression {
}
throw new InvalidDataAccessApiUsageException(
String.format("Invalid value in condition. Supported: DBObject, Field references, Criteria, got: %s", value));
String.format("Invalid value in condition. Supported: Document, Field references, Criteria, got: %s", value));
}
private List<Object> getClauses(AggregationOperationContext context, Document mappedObject) {
@ -173,7 +170,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -173,7 +170,7 @@ public class ConditionalOperator implements AggregationExpression {
}
}
clauses.add(new BasicDBObject(key, args));
clauses.add(new Document(key, args));
} else if (predicate instanceof Document) {
@ -188,7 +185,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -188,7 +185,7 @@ public class ConditionalOperator implements AggregationExpression {
List<Object> args = new ArrayList<Object>();
args.add("$" + key);
args.add(nested.get(s));
clauses.add(new BasicDBObject(s, args));
clauses.add(new Document(s, args));
}
} else if (!isKeyword(key)) {
@ -196,7 +193,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -196,7 +193,7 @@ public class ConditionalOperator implements AggregationExpression {
List<Object> args = new ArrayList<Object>();
args.add("$" + key);
args.add(predicate);
clauses.add(new BasicDBObject("$eq", args));
clauses.add(new Document("$eq", args));
}
return clauses;
@ -271,7 +268,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -271,7 +268,7 @@ public class ConditionalOperator implements AggregationExpression {
public static interface ThenBuilder {
/**
* @param value the value to be used if the condition evaluates {@literal true}. Can be a {@link DBObject}, a value
* @param value the value to be used if the condition evaluates {@literal true}. Can be a {@link Document}, a value
* that is supported by MongoDB or a value that can be converted to a MongoDB representation but must not
* be {@literal null}.
* @return the {@link OtherwiseBuilder}
@ -285,7 +282,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -285,7 +282,7 @@ public class ConditionalOperator implements AggregationExpression {
public static interface OtherwiseBuilder {
/**
* @param value the value to be used if the condition evaluates {@literal false}. Can be a {@link DBObject}, a value
* @param value the value to be used if the condition evaluates {@literal false}. Can be a {@link Document}, a value
* that is supported by MongoDB or a value that can be converted to a MongoDB representation but must not
* be {@literal null}.
* @return the {@link ConditionalOperator}
@ -317,7 +314,7 @@ public class ConditionalOperator implements AggregationExpression { @@ -317,7 +314,7 @@ public class ConditionalOperator implements AggregationExpression {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.ConditionalOperator.WhenBuilder#when(com.mongodb.DBObject)
* @see org.springframework.data.mongodb.core.aggregation.ConditionalOperator.WhenBuilder#when(org.bson.Document)
*/
@Override
public ConditionalExpressionBuilder when(Document booleanExpression) {

10
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/IfNullOperator.java

@ -13,7 +13,6 @@ @@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.aggregation;
import java.util.ArrayList;
@ -22,9 +21,6 @@ import java.util.List; @@ -22,9 +21,6 @@ import java.util.List;
import org.bson.Document;
import org.springframework.util.Assert;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Encapsulates the aggregation framework {@code $ifNull} operator. Replacement values can be either {@link Field field
* references}, values of simple MongoDB types or values that can be converted to a simple MongoDB type.
@ -56,7 +52,7 @@ public class IfNullOperator implements AggregationExpression { @@ -56,7 +52,7 @@ public class IfNullOperator implements AggregationExpression {
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.aggregation.AggregationExpression#toDbObject(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
* @see org.springframework.data.mongodb.core.aggregation.AggregationExpression#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext)
*/
@Override
public Document toDocument(AggregationOperationContext context) {
@ -73,7 +69,7 @@ public class IfNullOperator implements AggregationExpression { @@ -73,7 +69,7 @@ public class IfNullOperator implements AggregationExpression {
if (value instanceof Field) {
return context.getReference((Field) value).toString();
} else if (value instanceof DBObject) {
} else if (value instanceof Document) {
return value;
}
@ -120,7 +116,7 @@ public class IfNullOperator implements AggregationExpression { @@ -120,7 +116,7 @@ public class IfNullOperator implements AggregationExpression {
/**
* @param value the value to be used if the {@code $ifNull }condition evaluates {@literal true}. Can be a
* {@link DBObject}, a value that is supported by MongoDB or a value that can be converted to a MongoDB
* {@link Document}, a value that is supported by MongoDB or a value that can be converted to a MongoDB
* representation but must not be {@literal null}.
* @return the {@link IfNullOperator}
*/

3
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefResolver.java

@ -30,6 +30,7 @@ import com.mongodb.DBRef; @@ -30,6 +30,7 @@ import com.mongodb.DBRef;
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.4
*/
public interface DbRefResolver {
@ -70,7 +71,7 @@ public interface DbRefResolver { @@ -70,7 +71,7 @@ public interface DbRefResolver {
/**
* Loads a given {@link List} of {@link DBRef}s from the datasource in one batch. The resulting {@link List} of
* {@link DBObject} will reflect the ordering of the {@link DBRef} passed in.<br />
* {@link Document} will reflect the ordering of the {@link DBRef} passed in.<br />
* The {@link DBRef} elements in the list must not reference different collections.
*
* @param dbRefs must not be {@literal null}.

4
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java

@ -46,7 +46,6 @@ import org.springframework.objenesis.ObjenesisStd; @@ -46,7 +46,6 @@ import org.springframework.objenesis.ObjenesisStd;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import com.mongodb.client.MongoDatabase;
@ -57,6 +56,7 @@ import com.mongodb.client.MongoDatabase; @@ -57,6 +56,7 @@ import com.mongodb.client.MongoDatabase;
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.4
*/
public class DefaultDbRefResolver implements DbRefResolver {
@ -438,7 +438,7 @@ public class DefaultDbRefResolver implements DbRefResolver { @@ -438,7 +438,7 @@ public class DefaultDbRefResolver implements DbRefResolver {
}
/**
* {@link Comparator} for sorting {@link DBObject} that have been loaded in random order by a predefined list of
* {@link Comparator} for sorting {@link Document} that have been loaded in random order by a predefined list of
* reference identifiers.
*
* @author Christoph Strobl

2
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java

@ -43,6 +43,7 @@ import com.mongodb.DBObject; @@ -43,6 +43,7 @@ import com.mongodb.DBObject;
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
*/
public class DefaultMongoTypeMapper extends DefaultTypeMapper<Bson> implements MongoTypeMapper {
@ -169,7 +170,6 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<Bson> implements M @@ -169,7 +170,6 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper<Bson> implements M
} else if (sink instanceof DBObject) {
((DBObject) sink).put(typeKey, alias);
}
}
}
}

44
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DBObjectAccessor.java → spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java

@ -38,22 +38,22 @@ import com.mongodb.DBObject; @@ -38,22 +38,22 @@ import com.mongodb.DBObject;
*/
class DocumentAccessor {
private final Bson dbObject;
private final Bson document;
/**
* Creates a new {@link DocumentAccessor} for the given {@link Document}.
*
* @param dbObject must be a {@link Document} effectively, must not be {@literal null}.
* @param document must be a {@link Document} effectively, must not be {@literal null}.
*/
public DocumentAccessor(Bson dbObject) {
public DocumentAccessor(Bson document) {
Assert.notNull(dbObject, "Document must not be null!");
Assert.notNull(document, "Document must not be null!");
if (!(dbObject instanceof Document) && !(dbObject instanceof DBObject)) {
Assert.isInstanceOf(Document.class, dbObject, "Given Document must be a Document or BasicDBObject!");
if (!(document instanceof Document) && !(document instanceof DBObject)) {
Assert.isInstanceOf(Document.class, document, "Given Bson must be a Document or DBObject!");
}
this.dbObject = dbObject;
this.document = document;
}
/**
@ -70,21 +70,21 @@ class DocumentAccessor { @@ -70,21 +70,21 @@ class DocumentAccessor {
String fieldName = prop.getFieldName();
if (!fieldName.contains(".")) {
BsonUtils.addToMap(dbObject, fieldName, value);
BsonUtils.addToMap(document, fieldName, value);
return;
}
Iterator<String> parts = Arrays.asList(fieldName.split("\\.")).iterator();
Bson dbObject = this.dbObject;
Bson document = this.document;
while (parts.hasNext()) {
String part = parts.next();
if (parts.hasNext()) {
dbObject = getOrCreateNestedDbObject(part, dbObject);
document = getOrCreateNestedDocument(part, document);
} else {
BsonUtils.addToMap(dbObject, part, value);
BsonUtils.addToMap(document, part, value);
}
}
}
@ -102,11 +102,11 @@ class DocumentAccessor { @@ -102,11 +102,11 @@ class DocumentAccessor {
String fieldName = property.getFieldName();
if (!fieldName.contains(".")) {
return BsonUtils.asMap(this.dbObject).get(fieldName);
return BsonUtils.asMap(this.document).get(fieldName);
}
Iterator<String> parts = Arrays.asList(fieldName.split("\\.")).iterator();
Map<String, Object> source = BsonUtils.asMap(this.dbObject);
Map<String, Object> source = BsonUtils.asMap(this.document);
Object result = null;
while (source != null && parts.hasNext()) {
@ -122,7 +122,7 @@ class DocumentAccessor { @@ -122,7 +122,7 @@ class DocumentAccessor {
}
/**
* Returns whether the underlying {@link DBObject} has a value ({@literal null} or non-{@literal null}) for the given
* Returns whether the underlying {@link Document} has a value ({@literal null} or non-{@literal null}) for the given
* {@link MongoPersistentProperty}.
*
* @param property must not be {@literal null}.
@ -136,22 +136,22 @@ class DocumentAccessor { @@ -136,22 +136,22 @@ class DocumentAccessor {
if (!fieldName.contains(".")) {
if (this.dbObject instanceof Document) {
return ((Document) this.dbObject).containsKey(fieldName);
if (this.document instanceof Document) {
return ((Document) this.document).containsKey(fieldName);
}
if (this.dbObject instanceof DBObject) {
return ((DBObject) this.dbObject).containsField(fieldName);
if (this.document instanceof DBObject) {
return ((DBObject) this.document).containsField(fieldName);
}
}
String[] parts = fieldName.split("\\.");
Map<String, Object> source;
if (this.dbObject instanceof Document) {
source = ((Document) this.dbObject);
if (this.document instanceof Document) {
source = ((Document) this.document);
}else {
source = ((DBObject) this.dbObject).toMap();
source = ((DBObject) this.document).toMap();
}
Object result = null;
@ -201,7 +201,7 @@ class DocumentAccessor { @@ -201,7 +201,7 @@ class DocumentAccessor {
* @param source must not be {@literal null}.
* @return
*/
private static Document getOrCreateNestedDbObject(String key, Bson source) {
private static Document getOrCreateNestedDocument(String key, Bson source) {
Object existing = BsonUtils.asMap(source).get(key);

0
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DBObjectPropertyAccessor.java → spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentPropertyAccessor.java

35
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java

@ -83,6 +83,7 @@ import com.mongodb.DBRef; @@ -83,6 +83,7 @@ import com.mongodb.DBRef;
* @author Thomas Darimont
* @author Christoph Strobl
* @author Jordi Llach
* @author Mark Paluch
*/
public class MappingMongoConverter extends AbstractMongoConverter implements ApplicationContextAware, ValueResolver {
@ -281,7 +282,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App @@ -281,7 +282,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
accessor.setProperty(idProperty, idValue);
}
final ObjectPath currentPath = path.push(result, entity, idValue != null ? documentAccessor.get(idProperty) : null);
final ObjectPath currentPath = path.push(result, entity, idValue != null ? documentAccessor.get(idProperty) : null);
// Set properties not already set in the constructor
entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
@ -780,11 +781,11 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App @@ -780,11 +781,11 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
* Writes the given simple value to the given {@link Document}. Will store enum names for enum values.
*
* @param value
* @param dbObject must not be {@literal null}.
* @param bson must not be {@literal null}.
* @param key must not be {@literal null}.
*/
private void writeSimpleInternal(Object value, Bson dbObject, String key) {
addToMap(dbObject, key, getPotentiallyConvertedSimpleWrite(value));
private void writeSimpleInternal(Object value, Bson bson, String key) {
addToMap(bson, key, getPotentiallyConvertedSimpleWrite(value));
}
private void writeSimpleInternal(Object value, Bson bson, MongoPersistentProperty property) {
@ -1017,14 +1018,19 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App @@ -1017,14 +1018,19 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
return map;
}
@SuppressWarnings("unchecked")
private Map<String, Object> asMap(Bson bson) {
if (bson instanceof Document) {
return (Document) bson;
}
if (bson instanceof DBObject) {
return ((DBObject) bson).toMap();
}
throw new IllegalArgumentException("o_O what's that? Cannot read values from " + bson.getClass());
throw new IllegalArgumentException(
String.format("Cannot read %s. as map. Given Bson must be a Document or DBObject!", bson.getClass()));
}
private void addToMap(Bson bson, String key, Object value) {
@ -1037,20 +1043,26 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App @@ -1037,20 +1043,26 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
((DBObject) bson).put(key, value);
return;
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
throw new IllegalArgumentException(
String.format("Cannot add key/value pair to %s. as map. Given Bson must be a Document or DBObject!",
bson.getClass()));
}
@SuppressWarnings("unchecked")
private void addAllToMap(Bson bson, Map value) {
if (bson instanceof Document) {
((Document) bson).putAll((Map) value);
((Document) bson).putAll(value);
return;
}
if (bson instanceof DBObject) {
((DBObject) bson).putAll((Map) value);
((DBObject) bson).putAll(value);
return;
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
throw new IllegalArgumentException(String.format(
"Cannot add all to %s. Given Bson must be a Document or DBObject.", bson.getClass()));
}
private void removeFromMap(Bson bson, String key) {
@ -1059,11 +1071,14 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App @@ -1059,11 +1071,14 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
((Document) bson).remove(key);
return;
}
if (bson instanceof DBObject) {
((DBObject) bson).removeField(key);
return;
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
throw new IllegalArgumentException(
String.format("Cannot remove from %s. Given Bson must be a Document or DBObject.", bson.getClass()));
}
/*

24
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverters.java

@ -42,14 +42,13 @@ import org.springframework.util.Assert; @@ -42,14 +42,13 @@ import org.springframework.util.Assert;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
import com.mongodb.DBObject;
/**
* Wrapper class to contain useful converters for the usage with Mongo.
*
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
*/
abstract class MongoConverters {
@ -77,7 +76,7 @@ abstract class MongoConverters { @@ -77,7 +76,7 @@ abstract class MongoConverters {
converters.add(DocumentToStringConverter.INSTANCE);
converters.add(TermToStringConverter.INSTANCE);
converters.add(NamedMongoScriptToDocumentConverter.INSTANCE);
converters.add(DocumentToNamedMongoScriptCoverter.INSTANCE);
converters.add(DocumentToNamedMongoScriptConverter.INSTANCE);
converters.add(CurrencyToStringConverter.INSTANCE);
converters.add(StringToCurrencyConverter.INSTANCE);
converters.add(AtomicIntegerToIntegerConverter.INSTANCE);
@ -208,10 +207,7 @@ abstract class MongoConverters { @@ -208,10 +207,7 @@ abstract class MongoConverters {
return null;
}
if (source instanceof Document) {
return ((Document) source).toJson();
}
return source.toString();
return source.toJson();
}
}
@ -234,7 +230,7 @@ abstract class MongoConverters { @@ -234,7 +230,7 @@ abstract class MongoConverters {
* @author Christoph Strobl
* @since 1.7
*/
public static enum DocumentToNamedMongoScriptCoverter implements Converter<Document, NamedMongoScript> {
public static enum DocumentToNamedMongoScriptConverter implements Converter<Document, NamedMongoScript> {
INSTANCE;
@ -245,16 +241,8 @@ abstract class MongoConverters { @@ -245,16 +241,8 @@ abstract class MongoConverters {
return null;
}
String id = null;
Object rawValue = null;
if (source instanceof Document) {
id = ((Document) source).get("_id").toString();
rawValue = ((Document) source).get("value");
} else if (source instanceof DBObject) {
id = ((DBObject) source).get("_id").toString();
rawValue = ((DBObject) source).get("value");
}
String id = source.get("_id").toString();
Object rawValue = source.get("value");
return new NamedMongoScript(id, ((Code) rawValue).getCode());
}

15
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java

@ -247,7 +247,7 @@ public class QueryMapper { @@ -247,7 +247,7 @@ public class QueryMapper {
if (keyword.isOrOrNor() || (keyword.hasIterableValue() && !keyword.isGeometry())) {
Iterable<?> conditions = keyword.getValue();
List newConditions = new ArrayList();
List<Object> newConditions = new ArrayList<Object>();
for (Object condition : conditions) {
newConditions.add(isDocument(condition) ? getMappedObject((Document) condition, entity)
@ -291,6 +291,7 @@ public class QueryMapper { @@ -291,6 +291,7 @@ public class QueryMapper {
* @param newKey the key the value will be bound to eventually
* @return
*/
@SuppressWarnings("unchecked")
protected Object getMappedValue(Field documentField, Object value) {
if (documentField.isIdField()) {
@ -475,6 +476,12 @@ public class QueryMapper { @@ -475,6 +476,12 @@ public class QueryMapper {
return value instanceof Document;
}
/**
* Checks whether the given value is a {@link DBObject}.
*
* @param value can be {@literal null}.
* @return
*/
protected final boolean isDBObject(Object value) {
return value instanceof DBObject;
}
@ -585,13 +592,13 @@ public class QueryMapper { @@ -585,13 +592,13 @@ public class QueryMapper {
this.value = BsonUtils.get(source, key);
}
public Keyword(Bson dbObject) {
public Keyword(Bson bson) {
Set<String> keys = BsonUtils.asMap(dbObject).keySet();
Set<String> keys = BsonUtils.asMap(bson).keySet();
Assert.isTrue(keys.size() == 1, "Can only use a single value Document!");
this.key = keys.iterator().next();
this.value = BsonUtils.get(dbObject, key);
this.value = BsonUtils.get(bson, key);
}
/**

23
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java

@ -30,6 +30,7 @@ import com.mongodb.util.JSON; @@ -30,6 +30,7 @@ import com.mongodb.util.JSON;
* @author Christoph Strobl
* @author Thomas Darimont
* @author John Willemin
* @author Mark Paluch
*/
public class BasicQuery extends Query {
@ -37,19 +38,41 @@ public class BasicQuery extends Query { @@ -37,19 +38,41 @@ public class BasicQuery extends Query {
private Document fieldsObject;
private Document sortObject;
/**
* Create a new {@link BasicQuery} given a JSON {@code query}.
*
* @param query may be {@literal null}.
*/
public BasicQuery(String query) {
this(query, null);
}
/**
* Create a new {@link BasicQuery} given a query {@link Document}.
*
* @param queryObject may be {@literal null}.
*/
public BasicQuery(Document queryObject) {
this(queryObject, null);
}
/**
* Create a new {@link BasicQuery} given a JSON {@code query} and {@code fields}.
*
* @param query may be {@literal null}.
* @param fields may be {@literal null}.
*/
public BasicQuery(String query, String fields) {
this.queryObject = query != null ? new Document(((DBObject) JSON.parse(query)).toMap()) : null;
this.fieldsObject = fields != null ? new Document(((DBObject) JSON.parse(fields)).toMap()) : null;
}
/**
* Create a new {@link BasicQuery} given a query {@link Document} and field specification {@link Document}.
*
* @param queryObject may be {@literal null}.
* @param fieldsObject may be {@literal null}.
*/
public BasicQuery(Document queryObject, Document fieldsObject) {
this.queryObject = queryObject;
this.fieldsObject = fieldsObject;

4
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Field.java

@ -28,6 +28,7 @@ import org.springframework.util.ObjectUtils; @@ -28,6 +28,7 @@ import org.springframework.util.ObjectUtils;
* @author Oliver Gierke
* @author Patryk Wasik
* @author Christoph Strobl
* @author Mark Paluch
*/
public class Field {
@ -89,8 +90,7 @@ public class Field { @@ -89,8 +90,7 @@ public class Field {
}
for (Entry<String, Criteria> entry : elemMatchs.entrySet()) {
Document dbObject = new Document("$elemMatch", entry.getValue().getCriteriaObject());
document.put(entry.getKey(), dbObject);
document.put(entry.getKey(), new Document("$elemMatch", entry.getValue().getCriteriaObject()));
}
if (postionKey != null) {

4
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbSerializer.java

@ -46,6 +46,7 @@ import com.querydsl.mongodb.MongodbSerializer; @@ -46,6 +46,7 @@ import com.querydsl.mongodb.MongodbSerializer;
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
*/
class SpringDataMongodbSerializer extends MongodbSerializer {
@ -121,8 +122,7 @@ class SpringDataMongodbSerializer extends MongodbSerializer { @@ -121,8 +122,7 @@ class SpringDataMongodbSerializer extends MongodbSerializer {
if (ID_KEY.equals(key)) {
DBObject superIdValue = super.asDBObject(key, value);
Document mappedIdValue = mapper.getMappedObject((BasicDBObject) superIdValue, null);
DBObject parsedId = (DBObject) JSON.parse(mappedIdValue.toJson());
return parsedId;
return (DBObject) JSON.parse(mappedIdValue.toJson());
}
return super.asDBObject(key, value instanceof Pattern ? value : converter.convertToMongoType(value));
}

26
spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java

@ -55,30 +55,4 @@ public class BsonUtils { @@ -55,30 +55,4 @@ public class BsonUtils {
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
}
public static void addAllToMap(Bson bson, Map value) {
if (bson instanceof Document) {
((Document) bson).putAll((Map) value);
return;
}
if (bson instanceof DBObject) {
((DBObject) bson).putAll((Map) value);
return;
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
}
public static void removeFromMap(Bson bson, String key) {
if (bson instanceof Document) {
((Document) bson).remove(key);
return;
}
if (bson instanceof DBObject) {
((DBObject) bson).removeField(key);
return;
}
throw new IllegalArgumentException("o_O what's that? Cannot add value to " + bson.getClass());
}
}

4
spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/NamedMongoScriptConvertsUnitTests.java

@ -25,7 +25,7 @@ import org.junit.runner.RunWith; @@ -25,7 +25,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.core.convert.MongoConverters.DocumentToNamedMongoScriptCoverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.DocumentToNamedMongoScriptConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.NamedMongoScriptToDocumentConverter;
import org.springframework.data.mongodb.core.convert.NamedMongoScriptConvertsUnitTests.DboToNamedMongoScriptConverterUnitTests;
import org.springframework.data.mongodb.core.convert.NamedMongoScriptConvertsUnitTests.NamedMongoScriptToDboConverterUnitTests;
@ -95,7 +95,7 @@ public class NamedMongoScriptConvertsUnitTests { @@ -95,7 +95,7 @@ public class NamedMongoScriptConvertsUnitTests {
*/
public static class DboToNamedMongoScriptConverterUnitTests {
DocumentToNamedMongoScriptCoverter converter = DocumentToNamedMongoScriptCoverter.INSTANCE;
DocumentToNamedMongoScriptConverter converter = DocumentToNamedMongoScriptConverter.INSTANCE;
/**
* @see DATAMONGO-479

32
src/main/asciidoc/reference/mapping.adoc

@ -122,7 +122,7 @@ In addition to these types, Spring Data MongoDB provides a set of built-in conve @@ -122,7 +122,7 @@ In addition to these types, Spring Data MongoDB provides a set of built-in conve
| native
| `{"value" : null}`
| `DBObject`
| `Document`
| native
| `{"value" : { … }}`
@ -392,7 +392,7 @@ The MappingMongoConverter can use metadata to drive the mapping of objects to do @@ -392,7 +392,7 @@ The MappingMongoConverter can use metadata to drive the mapping of objects to do
* `@TextIndexed` - applied at the field level to mark the field to be included in the text index.
* `@Language` - applied at the field level to set the language override property for text index.
* `@Transient` - by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database
* `@PersistenceConstructor` - marks a given constructor - even a package protected one - to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved DBObject.
* `@PersistenceConstructor` - marks a given constructor - even a package protected one - to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved Document.
* `@Value` - this annotation is part of the Spring Framework . Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key's value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like: `@Value("#root.myProperty")` where `root` refers to the root of the given document.
* `@Field` - applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.
* `@Version` - applied at field level is used for optimistic locking and checked for modification on save operations. The initial value is `zero` which is bumped automatically on every update.
@ -484,7 +484,7 @@ class OrderItem { @@ -484,7 +484,7 @@ class OrderItem {
// getters/setters ommitted
}
DBObject input = new BasicDBObject("id", "4711");
Document input = new Document("id", "4711");
input.put("unitPrice", 2.5);
input.put("qty",5);
OrderItem item = converter.read(OrderItem.class, input);
@ -599,7 +599,7 @@ Simply declaring these beans in your Spring ApplicationContext will cause them t @@ -599,7 +599,7 @@ Simply declaring these beans in your Spring ApplicationContext will cause them t
[[mapping-explicit-converters]]
=== Overriding Mapping with explicit Converters
When storing and querying your objects it is convenient to have a `MongoConverter` instance handle the mapping of all Java types to DBObjects. However, sometimes you may want the `MongoConverter` s do most of the work but allow you to selectively handle the conversion for a particular type or to optimize performance.
When storing and querying your objects it is convenient to have a `MongoConverter` instance handle the mapping of all Java types to Documents. However, sometimes you may want the `MongoConverter` s do most of the work but allow you to selectively handle the conversion for a particular type or to optimize performance.
To selectively handle the conversion yourself, register one or more one or more `org.springframework.core.convert.converter.Converter` instances with the MongoConverter.
@ -607,14 +607,14 @@ NOTE: Spring 3.0 introduced a core.convert package that provides a general type @@ -607,14 +607,14 @@ NOTE: Spring 3.0 introduced a core.convert package that provides a general type
The method `customConversions` in `AbstractMongoConfiguration` can be used to configure Converters. The examples <<mapping-configuration,here>> at the beginning of this chapter show how to perform the configuration using Java and XML.
Below is an example of a Spring Converter implementation that converts from a DBObject to a Person POJO.
Below is an example of a Spring Converter implementation that converts from a Document to a Person POJO.
[source,java]
----
@ReadingConverter
public class PersonReadConverter implements Converter<DBObject, Person> {
public class PersonReadConverter implements Converter<Document, Person> {
public Person convert(DBObject source) {
public Person convert(Document source) {
Person p = new Person((ObjectId) source.get("_id"), (String) source.get("name"));
p.setAge((Integer) source.get("age"));
return p;
@ -622,19 +622,19 @@ Below is an example of a Spring Converter implementation that converts from a DB @@ -622,19 +622,19 @@ Below is an example of a Spring Converter implementation that converts from a DB
}
----
Here is an example that converts from a Person to a DBObject.
Here is an example that converts from a Person to a Document.
[source,java]
----
@WritingConverter
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;
public class PersonWriteConverter implements Converter<Person, Document> {
public Document convert(Person source) {
Document document = new Document();
document.put("_id", source.getId());
document.put("name", source.getFirstName());
document.put("age", source.getAge());
return document;
}
}
----

77
src/main/asciidoc/reference/mongodb.adoc

@ -145,7 +145,7 @@ This will produce the following output @@ -145,7 +145,7 @@ This will produce the following output
[source]
----
10:01:32,062 DEBUG apping.MongoPersistentEntityIndexCreator: 80 - Analyzing class class org.spring.example.Person for index information.
10:01:32,265 DEBUG ramework.data.mongodb.core.MongoTemplate: 631 - insert DBObject containing fields: [_class, age, name] in collection: Person
10:01:32,265 DEBUG ramework.data.mongodb.core.MongoTemplate: 631 - insert Document containing fields: [_class, age, name] in collection: Person
10:01:32,765 DEBUG ramework.data.mongodb.core.MongoTemplate:1243 - findOne using query: { "name" : "Joe"} in db.collection: database.Person
10:01:32,953 INFO org.spring.mongodb.example.MongoApp: 25 - Person [id=4ddbba3c0be56b7e1b210166, name=Joe, age=34]
10:01:32,984 DEBUG ramework.data.mongodb.core.MongoTemplate: 375 - Dropped collection [database.person]
@ -424,7 +424,7 @@ NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across m @@ -424,7 +424,7 @@ NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across m
The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the interface `MongoConverter`. Spring provides two implementations, `SimpleMappingConverter` and `MongoMappingConverter`, but you can also write your own converter. Please refer to the section on MongoConverters for more detailed information.
The `MongoTemplate` class implements the interface `MongoOperations`. In as much as possible, the methods on `MongoOperations` are named after methods available on the MongoDB driver `Collection` object 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 MongoOperations 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 operations.
The `MongoTemplate` class implements the interface `MongoOperations`. In as much as possible, the methods on `MongoOperations` are named after methods available on the MongoDB driver `Collection` object 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 MongoOperations can be passed domain objects instead of `Document` and there are fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `Document` to specify the parameters for those operations.
NOTE: The preferred way to reference the operations on `MongoTemplate` instance is via its interface `MongoOperations`.
@ -506,7 +506,7 @@ public interface WriteConcernResolver { @@ -506,7 +506,7 @@ public interface WriteConcernResolver {
}
----
The passed in argument, MongoAction, is what you use to determine the `WriteConcern` value to be used or to use the value of the Template itself as a default. `MongoAction` contains the collection name being written to, the `java.lang.Class` of the POJO, the converted `DBObject`, as well as the operation as an enumeration (`MongoActionOperation`: REMOVE, UPDATE, INSERT, INSERT_LIST, SAVE) and a few other pieces of contextual information. For example,
The passed in argument, MongoAction, is what you use to determine the `WriteConcern` value to be used or to use the value of the Template itself as a default. `MongoAction` contains the collection name being written to, the `java.lang.Class` of the POJO, the converted `Document`, as well as the operation as an enumeration (`MongoActionOperation`: REMOVE, UPDATE, INSERT, INSERT_LIST, SAVE) and a few other pieces of contextual information. For example,
[source]
----
@ -624,7 +624,7 @@ This would produce the following log output (including debug messages from `Mong @@ -624,7 +624,7 @@ This would produce the following log output (including debug messages from `Mong
[source]
----
DEBUG apping.MongoPersistentEntityIndexCreator: 80 - Analyzing class class org.spring.example.Person for index information.
DEBUG work.data.mongodb.core.MongoTemplate: 632 - insert DBObject containing fields: [_class, age, name] in collection: person
DEBUG work.data.mongodb.core.MongoTemplate: 632 - insert Document 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.mongodb.core.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]
@ -769,7 +769,7 @@ Note that we are extending the `AbstractMongoConfiguration` class and override t @@ -769,7 +769,7 @@ Note that we are extending the `AbstractMongoConfiguration` class and override t
[[mongo-template.save-insert]]
=== Methods for saving and inserting documents
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>`.
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, Document>` and `Converter<Document, Person>`.
NOTE: The difference between insert and save operations is that a save operation will perform an insert if the object is not already present.
@ -912,7 +912,7 @@ template.upsert(query(where("ssn").is(1111).and("firstName").is("Joe").and("Frai @@ -912,7 +912,7 @@ template.upsert(query(where("ssn").is(1111).and("firstName").is("Joe").and("Frai
[[mongo-template.find-and-upsert]]
=== Finding and Upserting documents in a collection
The `findAndModify(…)` method on DBCollection can update a document and return either the old or newly updated document in a single operation. `MongoTemplate` provides a findAndModify method that takes `Query` and `Update` classes and converts from `DBObject` to your POJOs. Here are the methods
The `findAndModify(…)` method on DBCollection can update a document and return either the old or newly updated document in a single operation. `MongoTemplate` provides a findAndModify method that takes `Query` and `Update` classes and converts from `Document` to your POJOs. Here are the methods
[source,java]
----
@ -1592,7 +1592,7 @@ public class XObject { @@ -1592,7 +1592,7 @@ public class XObject {
}
----
You can also obtain the raw result as a `DbObject` by calling the method `getRawResults` on the `GroupByResults` class.
You can also obtain the raw result as a `Document` by calling the method `getRawResults` on the `GroupByResults` class.
There is an additional method overload of the group method on `MongoOperations` which lets you specify a `Criteria` object for selecting a subset of the rows. An example which uses a `Criteria` object, with some syntax sugar using static imports, as well as referencing a key-function and reduce function javascript files via a Spring Resource string is shown below.
@ -1632,7 +1632,7 @@ An `AggregationOperation` represents a MongoDB aggregation pipeline operation an @@ -1632,7 +1632,7 @@ An `AggregationOperation` represents a MongoDB aggregation pipeline operation an
+
* `AggregationResults`
+
`AggregationResults` is the container for the result of an aggregate operation. It provides access to the raw aggregation result in the form of an `DBObject`, to the mapped objects and information which performed the aggregation.
`AggregationResults` is the container for the result of an aggregate operation. It provides access to the raw aggregation result in the form of an `Document`, to the mapped objects and information which performed the aggregation.
+
The canonical example for using the Spring Data MongoDB support for the MongoDB Aggregation Framework looks as follows:
@ -1914,8 +1914,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class, @@ -1914,8 +1914,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class,
.and("spaceUnits").mod(2).as("spaceUnitsMod2")
);
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
----
Note that we derive the name of the input-collection from the `Product`-class passed as first parameter to the `newAggregation`-Method.
@ -1950,8 +1950,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class, @@ -1950,8 +1950,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class,
);
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
----
[[mongo.aggregation.examples.example6]]
@ -1982,8 +1982,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class, @@ -1982,8 +1982,8 @@ TypedAggregation<Product> agg = newAggregation(Product.class,
.andExpression("(netPrice * (1-discountRate) + [0]) * (1+taxRate)", shippingCosts).as("salesPrice")
);
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();
AggregationResults<Document> result = mongoTemplate.aggregate(agg, Document.class);
List<Document> resultList = result.getMappedResults();
----
Note that we can also refer to other fields of the document within the SpEL expression.
@ -2044,23 +2044,22 @@ NOTE: For more information on the Spring type conversion service see the referen @@ -2044,23 +2044,22 @@ NOTE: For more information on the Spring type conversion service see the referen
[[mongo.custom-converters.writer]]
=== 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
An example implementation of the `Converter` that converts from a Person object to a `org.bson.Document` is shown below
[source,java]
----
import org.springframework.core.convert.converter.Converter;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.Document;
public class PersonWriteConverter implements Converter<Person, DBObject> {
public class PersonWriteConverter implements Converter<Person, Document> {
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;
public Document convert(Person source) {
Document document = new Document();
document.put("_id", source.getId());
document.put("name", source.getFirstName());
document.put("age", source.getAge());
return document;
}
}
----
@ -2068,13 +2067,13 @@ public class PersonWriteConverter implements Converter<Person, DBObject> { @@ -2068,13 +2067,13 @@ public class PersonWriteConverter implements Converter<Person, DBObject> {
[[mongo.custom-converters.reader]]
=== Reading using a Spring Converter
An example implementation of a Converter that converts from a DBObject to a Person object is shown below.
An example implementation of a Converter that converts from a Document to a Person object is shown below.
[source,java]
----
public class PersonReadConverter implements Converter<DBObject, Person> {
public class PersonReadConverter implements Converter<Document, Person> {
public Person convert(DBObject source) {
public Person convert(Document source) {
Person p = new Person((ObjectId) source.get("_id"), (String) source.get("name"));
p.setAge((Integer) source.get("age"));
return p;
@ -2225,7 +2224,7 @@ You can also get at the MongoDB driver's `DB.command( )` method using the `execu @@ -2225,7 +2224,7 @@ You can also get at the MongoDB driver's `DB.command( )` method using the `execu
[[mongo-template.commands.execution]]
=== Methods for executing commands
* `CommandResult` *executeCommand* `(DBObject command)` Execute a MongoDB command.
* `CommandResult` *executeCommand* `(Document command)` Execute a MongoDB command.
* `CommandResult` *executeCommand* `(String jsonCommand)` Execute the a MongoDB command expressed as a JSON string.
[[mongodb.mapping-usage.events]]
@ -2233,7 +2232,7 @@ You can also get at the MongoDB driver's `DB.command( )` method using the `execu @@ -2233,7 +2232,7 @@ You can also get at the MongoDB driver's `DB.command( )` method using the `execu
Built into the MongoDB mapping framework are several `org.springframework.context.ApplicationEvent` events that your application can respond to by registering special beans in the `ApplicationContext`. By being based off Spring's ApplicationContext event infrastructure this enables other products, such as Spring Integration, to easily receive these events as they are a well known eventing mechanism in Spring based applications.
To intercept an object before it goes through the conversion process (which turns your domain object into a `com.mongodb.DBObject`), you'd register a subclass of `AbstractMongoEventListener` that overrides the `onBeforeConvert` method. When the event is dispatched, your listener will be called and passed the domain object before it goes into the converter.
To intercept an object before it goes through the conversion process (which turns your domain object into a `org.bson.Document`), you'd register a subclass of `AbstractMongoEventListener` that overrides the `onBeforeConvert` method. When the event is dispatched, your listener will be called and passed the domain object before it goes into the converter.
====
[source,java]
@ -2247,7 +2246,7 @@ public class BeforeConvertListener extends AbstractMongoEventListener<Person> { @@ -2247,7 +2246,7 @@ public class BeforeConvertListener extends AbstractMongoEventListener<Person> {
----
====
To intercept an object before it goes into the database, you'd register a subclass of `org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener` that overrides the `onBeforeSave` method. When the event is dispatched, your listener will be called and passed the domain object and the converted `com.mongodb.DBObject`.
To intercept an object before it goes into the database, you'd register a subclass of `org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener` that overrides the `onBeforeSave` method. When the event is dispatched, your listener will be called and passed the domain object and the converted `com.mongodb.Document`.
====
[source,java]
@ -2265,11 +2264,11 @@ Simply declaring these beans in your Spring ApplicationContext will cause them t @@ -2265,11 +2264,11 @@ Simply declaring these beans in your Spring ApplicationContext will cause them t
The list of callback methods that are present in AbstractMappingEventListener are
* `onBeforeConvert` - called in MongoTemplate insert, insertList and save operations before the object is converted to a DBObject using a MongoConveter.
* `onBeforeSave` - called in MongoTemplate insert, insertList and save operations *before* inserting/saving the DBObject in the database.
* `onAfterSave` - called in MongoTemplate insert, insertList and save operations *after* inserting/saving the DBObject in the database.
* `onAfterLoad` - called in MongoTemplate find, findAndRemove, findOne and getCollection methods after the DBObject is retrieved from the database.
* `onAfterConvert` - called in MongoTemplate find, findAndRemove, findOne and getCollection methods after the DBObject retrieved from the database was converted to a POJO.
* `onBeforeConvert` - called in MongoTemplate insert, insertList and save operations before the object is converted to a Document using a MongoConveter.
* `onBeforeSave` - called in MongoTemplate insert, insertList and save operations *before* inserting/saving the Document in the database.
* `onAfterSave` - called in MongoTemplate insert, insertList and save operations *after* inserting/saving the Document in the database.
* `onAfterLoad` - called in MongoTemplate find, findAndRemove, findOne and getCollection methods after the Document is retrieved from the database.
* `onAfterConvert` - called in MongoTemplate find, findAndRemove, findOne and getCollection methods after the Document retrieved from the database was converted to a POJO.
[[mongo.exception]]
== Exception Translation
@ -2303,9 +2302,9 @@ Here is an example that uses the `CollectionCallback` to return information abou @@ -2303,9 +2302,9 @@ Here is an example that uses the `CollectionCallback` to return information abou
----
boolean hasIndex = template.execute("geolocation", new CollectionCallbackBoolean>() {
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"))) {
List<Document> indexes = collection.getIndexInfo();
for (Document document : indexes) {
if ("location_2d".equals(document.get("name"))) {
return true;
}
}
@ -2386,7 +2385,7 @@ class GridFsClient { @@ -2386,7 +2385,7 @@ class GridFsClient {
----
====
The `store(…)` operations take an `InputStream`, a filename and optionally metadata information about the file to store. The metadata can be an arbitrary object which will be marshaled by the `MongoConverter` configured with the `GridFsTemplate`. Alternatively you can also provide a `DBObject` as well.
The `store(…)` operations take an `InputStream`, a filename and optionally metadata information about the file to store. The metadata can be an arbitrary object which will be marshaled by the `MongoConverter` configured with the `GridFsTemplate`. Alternatively you can also provide a `Document` as well.
Reading files from the filesystem can either be achieved through the `find(…)` or `getResources(…)` methods. Let's have a look at the `find(…)` methods first. You can either find a single file matching a `Query` or multiple ones. To easily define file queries we provide the `GridFsCriteria` helper class. It provides static factory methods to encapsulate default metadata fields (e.g. `whereFilename()`, `whereContentType()`) or the custom one through `whereMetaData()`.

Loading…
Cancel
Save