Compare commits
39 Commits
4.0.x
...
1.9.3.RELE
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
557a528690 | ||
|
|
762569c826 | ||
|
|
ad7d82f521 | ||
|
|
04deaacbec | ||
|
|
ec443f2b5e | ||
|
|
f1b04ff354 | ||
|
|
62dd7d070a | ||
|
|
5df92a86a3 | ||
|
|
2ca3df1ff4 | ||
|
|
a8751249fd | ||
|
|
19abff826e | ||
|
|
5f199cf81f | ||
|
|
eb26b78a19 | ||
|
|
3d0053c61a | ||
|
|
7b15d246e8 | ||
|
|
b75f4a2834 | ||
|
|
d6ac4c6df5 | ||
|
|
02f56c88f5 | ||
|
|
cd35b9ed2a | ||
|
|
e8944a6c3a | ||
|
|
6fcbc225eb | ||
|
|
f06eda488c | ||
|
|
0ef910445d | ||
|
|
b22ee9d27c | ||
|
|
859a0e83c8 | ||
|
|
b35f151b80 | ||
|
|
17afb07e45 | ||
|
|
b407963344 | ||
|
|
8b31ba1836 | ||
|
|
0cf6edae43 | ||
|
|
0824105377 | ||
|
|
dc936a5b7b | ||
|
|
c8fe02e48e | ||
|
|
32547db306 | ||
|
|
41902154ca | ||
|
|
2354ced1bf | ||
|
|
791cc3a1b8 | ||
|
|
021c03fbbf | ||
|
|
e4a59f29d0 |
19
.travis.yml
19
.travis.yml
@@ -3,13 +3,28 @@ language: java
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
services:
|
||||
- mongodb
|
||||
before_script:
|
||||
- mongod --version
|
||||
|
||||
env:
|
||||
matrix:
|
||||
- PROFILE=ci
|
||||
- PROFILE=mongo-next
|
||||
- PROFILE=mongo3
|
||||
- PROFILE=mongo3-next
|
||||
- PROFILE=mongo31
|
||||
- PROFILE=mongo32
|
||||
- PROFILE=mongo33
|
||||
|
||||
# Current MongoDB version is 2.4.2 as of 2016-04, see https://github.com/travis-ci/travis-ci/issues/3694
|
||||
# apt-get starts a MongoDB instance so it's not started using before_script
|
||||
addons:
|
||||
apt:
|
||||
sources:
|
||||
- mongodb-3.2-precise
|
||||
packages:
|
||||
- mongodb-org-server
|
||||
- mongodb-org-shell
|
||||
|
||||
sudo: false
|
||||
|
||||
|
||||
25
pom.xml
25
pom.xml
@@ -5,7 +5,7 @@
|
||||
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb-parent</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>Spring Data MongoDB</name>
|
||||
@@ -15,7 +15,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.data.build</groupId>
|
||||
<artifactId>spring-data-parent</artifactId>
|
||||
<version>1.8.0.RELEASE</version>
|
||||
<version>1.8.3.RELEASE</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
@@ -28,8 +28,8 @@
|
||||
<properties>
|
||||
<project.type>multi</project.type>
|
||||
<dist.id>spring-data-mongodb</dist.id>
|
||||
<springdata.commons>1.12.0.RELEASE</springdata.commons>
|
||||
<mongo>2.14.0</mongo>
|
||||
<springdata.commons>1.12.3.RELEASE</springdata.commons>
|
||||
<mongo>2.14.3</mongo>
|
||||
<mongo.osgi>2.13.0</mongo.osgi>
|
||||
</properties>
|
||||
|
||||
@@ -107,7 +107,7 @@
|
||||
|
||||
<id>mongo-next</id>
|
||||
<properties>
|
||||
<mongo>2.14.0-SNAPSHOT</mongo>
|
||||
<mongo>2.15.0-SNAPSHOT</mongo>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
@@ -148,16 +148,25 @@
|
||||
|
||||
<id>mongo31</id>
|
||||
<properties>
|
||||
<mongo>3.1.0</mongo>
|
||||
<mongo>3.1.1</mongo>
|
||||
</properties>
|
||||
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
|
||||
<id>mongo32-next</id>
|
||||
<id>mongo32</id>
|
||||
<properties>
|
||||
<mongo>3.2.0-SNAPSHOT</mongo>
|
||||
<mongo>3.2.2</mongo>
|
||||
</properties>
|
||||
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
|
||||
<id>mongo33</id>
|
||||
<properties>
|
||||
<mongo>3.3.0</mongo>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb-parent</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb-parent</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb-parent</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-mongodb-parent</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
<version>1.9.3.RELEASE</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2015 the original author or authors.
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -98,7 +98,7 @@ class DefaultScriptOperations implements ScriptOperations {
|
||||
|
||||
@Override
|
||||
public Object doInDB(DB db) throws MongoException, DataAccessException {
|
||||
return db.eval(script.getCode(), convertScriptArgs(args));
|
||||
return db.eval(script.getCode(), convertScriptArgs(false, args));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -155,7 +155,7 @@ class DefaultScriptOperations implements ScriptOperations {
|
||||
return scriptNames;
|
||||
}
|
||||
|
||||
private Object[] convertScriptArgs(Object... args) {
|
||||
private Object[] convertScriptArgs(boolean quote, Object... args) {
|
||||
|
||||
if (ObjectUtils.isEmpty(args)) {
|
||||
return args;
|
||||
@@ -164,15 +164,15 @@ class DefaultScriptOperations implements ScriptOperations {
|
||||
List<Object> convertedValues = new ArrayList<Object>(args.length);
|
||||
|
||||
for (Object arg : args) {
|
||||
convertedValues.add(arg instanceof String ? String.format("'%s'", arg) : this.mongoOperations.getConverter()
|
||||
.convertToMongoType(arg));
|
||||
convertedValues.add(arg instanceof String && quote ? String.format("'%s'", arg)
|
||||
: this.mongoOperations.getConverter().convertToMongoType(arg));
|
||||
}
|
||||
|
||||
return convertedValues.toArray();
|
||||
}
|
||||
|
||||
private String convertAndJoinScriptArgs(Object... args) {
|
||||
return ObjectUtils.isEmpty(args) ? "" : StringUtils.arrayToCommaDelimitedString(convertScriptArgs(args));
|
||||
return ObjectUtils.isEmpty(args) ? "" : StringUtils.arrayToCommaDelimitedString(convertScriptArgs(true, args));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2015 the original author or authors.
|
||||
* Copyright 2015-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,16 +20,17 @@ import com.mongodb.DBObject;
|
||||
/**
|
||||
* An {@link AggregationExpression} can be used with field expressions in aggregation pipeline stages like
|
||||
* {@code project} and {@code group}.
|
||||
*
|
||||
*
|
||||
* @author Thomas Darimont
|
||||
* @author Oliver Gierke
|
||||
* @author Christoph Strobl
|
||||
*/
|
||||
interface AggregationExpression {
|
||||
public interface AggregationExpression {
|
||||
|
||||
/**
|
||||
* Turns the {@link AggregationExpression} into a {@link DBObject} within the given
|
||||
* {@link AggregationOperationContext}.
|
||||
*
|
||||
*
|
||||
* @param context
|
||||
* @return
|
||||
*/
|
||||
|
||||
@@ -114,6 +114,40 @@ class DBObjectAccessor {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the underlying {@link DBObject} has a value ({@literal null} or non-{@literal null}) for the given
|
||||
* {@link MongoPersistentProperty}.
|
||||
*
|
||||
* @param property must not be {@literal null}.
|
||||
* @return
|
||||
*/
|
||||
public boolean hasValue(MongoPersistentProperty property) {
|
||||
|
||||
Assert.notNull(property, "Property must not be null!");
|
||||
|
||||
String fieldName = property.getFieldName();
|
||||
|
||||
if (!fieldName.contains(".")) {
|
||||
return this.dbObject.containsField(fieldName);
|
||||
}
|
||||
|
||||
String[] parts = fieldName.split("\\.");
|
||||
Map<String, Object> source = this.dbObject;
|
||||
Object result = null;
|
||||
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
|
||||
result = source.get(parts[i - 1]);
|
||||
source = getAsMap(result);
|
||||
|
||||
if (source == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return source.containsKey(parts[parts.length - 1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given source object as map, i.e. {@link BasicDBObject}s and maps as is or {@literal null} otherwise.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2015 the original author or authors.
|
||||
* Copyright 2013-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -180,8 +180,8 @@ public class DefaultDbRefResolver implements DbRefResolver {
|
||||
* @author Oliver Gierke
|
||||
* @author Christoph Strobl
|
||||
*/
|
||||
static class LazyLoadingInterceptor implements MethodInterceptor, org.springframework.cglib.proxy.MethodInterceptor,
|
||||
Serializable {
|
||||
static class LazyLoadingInterceptor
|
||||
implements MethodInterceptor, org.springframework.cglib.proxy.MethodInterceptor, Serializable {
|
||||
|
||||
private static final Method INITIALIZE_METHOD, TO_DBREF_METHOD, FINALIZE_METHOD;
|
||||
|
||||
@@ -387,7 +387,8 @@ public class DefaultDbRefResolver implements DbRefResolver {
|
||||
} catch (RuntimeException ex) {
|
||||
|
||||
DataAccessException translatedException = this.exceptionTranslator.translateExceptionIfPossible(ex);
|
||||
throw new LazyLoadingException("Unable to lazily resolve DBRef!", translatedException);
|
||||
throw new LazyLoadingException("Unable to lazily resolve DBRef!",
|
||||
translatedException != null ? translatedException : ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2015 the original author or authors.
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -599,7 +599,7 @@ abstract class GeoConverters {
|
||||
Assert.isTrue(ObjectUtils.nullSafeEquals(source.get("type"), "Point"),
|
||||
String.format("Cannot convert type '%s' to Point.", source.get("type")));
|
||||
|
||||
List<Double> dbl = (List<Double>) source.get("coordinates");
|
||||
List<Number> dbl = (List<Number>) source.get("coordinates");
|
||||
return new GeoJsonPoint(dbl.get(0).doubleValue(), dbl.get(1).doubleValue());
|
||||
}
|
||||
}
|
||||
@@ -832,7 +832,7 @@ abstract class GeoConverters {
|
||||
|
||||
Assert.isInstanceOf(List.class, point);
|
||||
|
||||
List<Double> coordinatesList = (List<Double>) point;
|
||||
List<Number> coordinatesList = (List<Number>) point;
|
||||
|
||||
points.add(new GeoJsonPoint(coordinatesList.get(0).doubleValue(), coordinatesList.get(1).doubleValue()));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2011-2015 by the original author(s).
|
||||
* Copyright 2011-2016 by the original author(s).
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,6 +20,7 @@ import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
@@ -259,7 +260,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
// make sure id property is set before all other properties
|
||||
Object idValue = null;
|
||||
|
||||
if (idProperty != null) {
|
||||
if (idProperty != null && new DBObjectAccessor(dbo).hasValue(idProperty)) {
|
||||
idValue = getValueInternal(idProperty, dbo, evaluator, path);
|
||||
accessor.setProperty(idProperty, idValue);
|
||||
}
|
||||
@@ -896,9 +897,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
Collection<Object> items = targetType.getType().isArray() ? new ArrayList<Object>()
|
||||
: CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size());
|
||||
|
||||
for (int i = 0; i < sourceValue.size(); i++) {
|
||||
|
||||
Object dbObjItem = sourceValue.get(i);
|
||||
for (Object dbObjItem : sourceValue) {
|
||||
|
||||
if (dbObjItem instanceof DBRef) {
|
||||
items.add(
|
||||
@@ -992,20 +991,32 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App
|
||||
}
|
||||
|
||||
if (obj instanceof DBObject) {
|
||||
|
||||
DBObject newValueDbo = new BasicDBObject();
|
||||
|
||||
for (String vk : ((DBObject) obj).keySet()) {
|
||||
|
||||
Object o = ((DBObject) obj).get(vk);
|
||||
newValueDbo.put(vk, convertToMongoType(o, typeHint));
|
||||
}
|
||||
|
||||
return newValueDbo;
|
||||
}
|
||||
|
||||
if (obj instanceof Map) {
|
||||
DBObject result = new BasicDBObject();
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) obj).entrySet()) {
|
||||
result.put(entry.getKey().toString(), convertToMongoType(entry.getValue(), typeHint));
|
||||
|
||||
Map<Object, Object> converted = new LinkedHashMap<Object, Object>();
|
||||
|
||||
for (Entry<Object, Object> entry : ((Map<Object, Object>) obj).entrySet()) {
|
||||
|
||||
TypeInformation<? extends Object> valueTypeHint = typeHint != null && typeHint.getMapValueType() != null
|
||||
? typeHint.getMapValueType() : typeHint;
|
||||
|
||||
converted.put(getPotentiallyConvertedSimpleWrite(entry.getKey()).toString(),
|
||||
convertToMongoType(entry.getValue(), valueTypeHint));
|
||||
}
|
||||
return result;
|
||||
|
||||
return new BasicDBObject(converted);
|
||||
}
|
||||
|
||||
if (obj.getClass().isArray()) {
|
||||
|
||||
@@ -81,7 +81,10 @@ abstract class MongoConverters {
|
||||
converters.add(DBObjectToNamedMongoScriptCoverter.INSTANCE);
|
||||
converters.add(CurrencyToStringConverter.INSTANCE);
|
||||
converters.add(StringToCurrencyConverter.INSTANCE);
|
||||
converters.add(NumberToNumberConverterFactory.INSTANCE);
|
||||
converters.add(AtomicIntegerToIntegerConverter.INSTANCE);
|
||||
converters.add(AtomicLongToLongConverter.INSTANCE);
|
||||
converters.add(LongToAtomicLongConverter.INSTANCE);
|
||||
converters.add(IntegerToAtomicIntegerConverter.INSTANCE);
|
||||
|
||||
return converters;
|
||||
}
|
||||
@@ -374,4 +377,68 @@ abstract class MongoConverters {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ConverterFactory} implementation converting {@link AtomicLong} into {@link Long}.
|
||||
*
|
||||
* @author Christoph Strobl
|
||||
* @since 1.10
|
||||
*/
|
||||
@WritingConverter
|
||||
public static enum AtomicLongToLongConverter implements Converter<AtomicLong, Long> {
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public Long convert(AtomicLong source) {
|
||||
return NumberUtils.convertNumberToTargetClass(source, Long.class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ConverterFactory} implementation converting {@link AtomicInteger} into {@link Integer}.
|
||||
*
|
||||
* @author Christoph Strobl
|
||||
* @since 1.10
|
||||
*/
|
||||
@WritingConverter
|
||||
public static enum AtomicIntegerToIntegerConverter implements Converter<AtomicInteger, Integer> {
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public Integer convert(AtomicInteger source) {
|
||||
return NumberUtils.convertNumberToTargetClass(source, Integer.class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ConverterFactory} implementation converting {@link Long} into {@link AtomicLong}.
|
||||
*
|
||||
* @author Christoph Strobl
|
||||
* @since 1.10
|
||||
*/
|
||||
@ReadingConverter
|
||||
public static enum LongToAtomicLongConverter implements Converter<Long, AtomicLong> {
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public AtomicLong convert(Long source) {
|
||||
return source != null ? new AtomicLong(source) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link ConverterFactory} implementation converting {@link Integer} into {@link AtomicInteger}.
|
||||
*
|
||||
* @author Christoph Strobl
|
||||
* @since 1.10
|
||||
*/
|
||||
@ReadingConverter
|
||||
public static enum IntegerToAtomicIntegerConverter implements Converter<Integer, AtomicInteger> {
|
||||
INSTANCE;
|
||||
|
||||
@Override
|
||||
public AtomicInteger convert(Integer source) {
|
||||
return source != null ? new AtomicInteger(source) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ import com.mongodb.DBRef;
|
||||
* @author Patryk Wasik
|
||||
* @author Thomas Darimont
|
||||
* @author Christoph Strobl
|
||||
* @author Mark Paluch
|
||||
*/
|
||||
public class QueryMapper {
|
||||
|
||||
@@ -66,7 +67,7 @@ public class QueryMapper {
|
||||
static final ClassTypeInformation<?> NESTED_DOCUMENT = ClassTypeInformation.from(NestedDocument.class);
|
||||
|
||||
private enum MetaMapping {
|
||||
FORCE, WHEN_PRESENT, IGNORE;
|
||||
FORCE, WHEN_PRESENT, IGNORE
|
||||
}
|
||||
|
||||
private final ConversionService conversionService;
|
||||
@@ -316,7 +317,7 @@ public class QueryMapper {
|
||||
}
|
||||
|
||||
if (isNestedKeyword(value)) {
|
||||
return getMappedKeyword(new Keyword((DBObject) value), null);
|
||||
return getMappedKeyword(new Keyword((DBObject) value), documentField.getPropertyEntity());
|
||||
}
|
||||
|
||||
if (isAssociationConversionNecessary(documentField, value)) {
|
||||
|
||||
@@ -200,7 +200,7 @@ class MongoQueryCreator extends AbstractQueryCreator<Query, Criteria> {
|
||||
case CONTAINING:
|
||||
return createContainingCriteria(part, property, criteria, parameters);
|
||||
case NOT_CONTAINING:
|
||||
return createContainingCriteria(part, property, criteria, parameters).not();
|
||||
return createContainingCriteria(part, property, criteria.not(), parameters);
|
||||
case REGEX:
|
||||
return criteria.regex(parameters.next().toString());
|
||||
case EXISTS:
|
||||
|
||||
@@ -26,9 +26,11 @@ import org.springframework.data.mongodb.core.convert.QueryMapper;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.DBRef;
|
||||
import com.querydsl.core.types.Constant;
|
||||
import com.querydsl.core.types.Path;
|
||||
import com.querydsl.core.types.PathMetadata;
|
||||
import com.querydsl.core.types.PathType;
|
||||
@@ -72,6 +74,20 @@ class SpringDataMongodbSerializer extends MongodbSerializer {
|
||||
this.mapper = new QueryMapper(converter);
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see com.querydsl.mongodb.MongodbSerializer#visit(com.querydsl.core.types.Constant, java.lang.Void)
|
||||
*/
|
||||
@Override
|
||||
public Object visit(Constant<?> expr, Void context) {
|
||||
|
||||
if (!ClassUtils.isAssignable(Enum.class, expr.getType())) {
|
||||
return super.visit(expr, context);
|
||||
}
|
||||
|
||||
return converter.convertToMongoType(expr.getConstant());
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
* @see com.querydsl.mongodb.MongodbSerializer#getKeyForPath(com.querydsl.core.types.Path, com.querydsl.core.types.PathMetadata)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2011-2012 the original author or authors.
|
||||
* Copyright 2011-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Ignore;
|
||||
@@ -37,6 +38,13 @@ import com.mongodb.CommandResult;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.ServerAddress;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Mark Pollack
|
||||
* @author Oliver Gierke
|
||||
* @author Thomas Darimont
|
||||
* @author Mark Paluch
|
||||
*/
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class MongoNamespaceReplicaSetTests {
|
||||
@@ -70,10 +78,13 @@ public class MongoNamespaceReplicaSetTests {
|
||||
|
||||
assertThat(replicaSetSeeds, is(notNullValue()));
|
||||
assertThat(replicaSetSeeds, hasSize(3));
|
||||
assertThat(
|
||||
replicaSetSeeds,
|
||||
hasItems(new ServerAddress("192.168.174.130", 27017), new ServerAddress("192.168.174.130", 27018),
|
||||
new ServerAddress("192.168.174.130", 27019)));
|
||||
|
||||
List<Integer> ports = new ArrayList<Integer>();
|
||||
for (ServerAddress replicaSetSeed : replicaSetSeeds) {
|
||||
ports.add(replicaSetSeed.getPort());
|
||||
}
|
||||
|
||||
assertThat(ports, hasItems(27017, 27018, 27019));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2014-2015 the original author or authors.
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -190,4 +190,12 @@ public class DefaultScriptOperationsTests {
|
||||
public void scriptNamesShouldReturnEmptySetWhenNoScriptRegistered() {
|
||||
assertThat(scriptOps.getScriptNames(), is(empty()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1465
|
||||
*/
|
||||
@Test
|
||||
public void executeShouldNotQuoteStrings() {
|
||||
assertThat(scriptOps.execute(EXECUTABLE_SCRIPT, "spring-data"), is((Object) "spring-data"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,20 @@ public class DBObjectAccessorUnitTests {
|
||||
assertThat(nestedA.get("c"), is((Object) "c"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1471
|
||||
*/
|
||||
@Test
|
||||
public void exposesAvailabilityOfFields() {
|
||||
|
||||
DBObjectAccessor accessor = new DBObjectAccessor(new BasicDBObject("a", new BasicDBObject("c", "d")));
|
||||
MongoPersistentEntity<?> entity = context.getPersistentEntity(ProjectingType.class);
|
||||
|
||||
assertThat(accessor.hasValue(entity.getPersistentProperty("foo")), is(false));
|
||||
assertThat(accessor.hasValue(entity.getPersistentProperty("a")), is(true));
|
||||
assertThat(accessor.hasValue(entity.getPersistentProperty("name")), is(false));
|
||||
}
|
||||
|
||||
static class ProjectingType {
|
||||
|
||||
String name;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.data.mongodb.core.convert;
|
||||
|
||||
import static org.hamcrest.core.Is.*;
|
||||
import static org.hamcrest.core.IsEqual.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.support.PersistenceExceptionTranslator;
|
||||
import org.springframework.data.mongodb.LazyLoadingException;
|
||||
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.LazyLoadingInterceptor;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
|
||||
|
||||
import com.mongodb.DBRef;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link LazyLoadingInterceptor}.
|
||||
*
|
||||
* @author Christoph Strobl
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class LazyLoadingInterceptorUnitTests {
|
||||
|
||||
public @Rule ExpectedException exception = ExpectedException.none();
|
||||
|
||||
@Mock MongoPersistentProperty propertyMock;
|
||||
@Mock DBRef dbrefMock;
|
||||
@Mock DbRefResolverCallback callbackMock;
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1437
|
||||
*/
|
||||
@Test
|
||||
public void shouldPreserveCauseForNonTranslatableExceptions() throws Throwable {
|
||||
|
||||
NullPointerException npe = new NullPointerException("Some Exception we did not think about.");
|
||||
when(callbackMock.resolve(propertyMock)).thenThrow(npe);
|
||||
|
||||
exception.expect(LazyLoadingException.class);
|
||||
exception.expectCause(is(equalTo(npe)));
|
||||
|
||||
new LazyLoadingInterceptor(propertyMock, dbrefMock, new NullExceptionTranslator(), callbackMock).intercept(null,
|
||||
LazyLoadingProxy.class.getMethod("getTarget"), null, null);
|
||||
}
|
||||
|
||||
static class NullExceptionTranslator implements PersistenceExceptionTranslator {
|
||||
|
||||
@Override
|
||||
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2066,6 +2066,14 @@ public class MappingMongoConverterUnitTests {
|
||||
assertThat(target.map.get(FooBarEnum.FOO), is("spring"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1471
|
||||
*/
|
||||
@Test
|
||||
public void readsDocumentWithPrimitiveIdButNoValue() {
|
||||
assertThat(converter.read(ClassWithIntId.class, new BasicDBObject()), is(notNullValue()));
|
||||
}
|
||||
|
||||
static class GenericType<T> {
|
||||
T content;
|
||||
}
|
||||
|
||||
@@ -15,11 +15,13 @@
|
||||
*/
|
||||
package org.springframework.data.mongodb.core.convert;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Currency;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.geo.Box;
|
||||
@@ -27,8 +29,12 @@ import org.springframework.data.geo.Circle;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.geo.Polygon;
|
||||
import org.springframework.data.geo.Shape;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.AtomicIntegerToIntegerConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.AtomicLongToLongConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.BigDecimalToStringConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.CurrencyToStringConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.IntegerToAtomicIntegerConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.LongToAtomicLongConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.StringToBigDecimalConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverters.StringToCurrencyConverter;
|
||||
import org.springframework.data.mongodb.core.geo.Sphere;
|
||||
@@ -140,4 +146,36 @@ public class MongoConvertersUnitTests {
|
||||
public void convertsStringToCurrencyCorrectly() {
|
||||
assertThat(StringToCurrencyConverter.INSTANCE.convert("USD"), is(Currency.getInstance("USD")));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1416
|
||||
*/
|
||||
@Test
|
||||
public void convertsAtomicLongToLongCorrectly() {
|
||||
assertThat(AtomicLongToLongConverter.INSTANCE.convert(new AtomicLong(100L)), is(100L));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1416
|
||||
*/
|
||||
@Test
|
||||
public void convertsAtomicIntegerToIntegerCorrectly() {
|
||||
assertThat(AtomicIntegerToIntegerConverter.INSTANCE.convert(new AtomicInteger(100)), is(100));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1416
|
||||
*/
|
||||
@Test
|
||||
public void convertsLongToAtomicLongCorrectly() {
|
||||
assertThat(LongToAtomicLongConverter.INSTANCE.convert(100L), is(instanceOf(AtomicLong.class)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1416
|
||||
*/
|
||||
@Test
|
||||
public void convertsIntegerToAtomicIntegerCorrectly() {
|
||||
assertThat(IntegerToAtomicIntegerConverter.INSTANCE.convert(100), is(instanceOf(AtomicInteger.class)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2011-2015 the original author or authors.
|
||||
* Copyright 2011-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -35,6 +35,7 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
@@ -54,6 +55,7 @@ import org.springframework.data.mongodb.core.mapping.TextScore;
|
||||
import org.springframework.data.mongodb.core.query.BasicQuery;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.test.util.BasicDbListBuilder;
|
||||
|
||||
import com.mongodb.BasicDBList;
|
||||
import com.mongodb.BasicDBObject;
|
||||
@@ -68,6 +70,7 @@ import com.mongodb.QueryBuilder;
|
||||
* @author Patryk Wasik
|
||||
* @author Thomas Darimont
|
||||
* @author Christoph Strobl
|
||||
* @author Mark Paluch
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class QueryMapperUnitTests {
|
||||
@@ -595,6 +598,28 @@ public class QueryMapperUnitTests {
|
||||
assertThat(dbo.toString(), equalTo("{ \"embedded\" : { \"$in\" : [ { \"_id\" : \"1\"} , { \"_id\" : \"2\"}]}}"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1406
|
||||
*/
|
||||
@Test
|
||||
public void shouldMapQueryForNestedCustomizedPropertiesUsingConfiguredFieldNames() {
|
||||
|
||||
EmbeddedClass embeddedClass = new EmbeddedClass();
|
||||
embeddedClass.customizedField = "hello";
|
||||
|
||||
Foo foo = new Foo();
|
||||
foo.listOfItems = Arrays.asList(embeddedClass);
|
||||
|
||||
Query query = new Query(Criteria.where("listOfItems") //
|
||||
.elemMatch(new Criteria(). //
|
||||
andOperator(Criteria.where("customizedField").is(embeddedClass.customizedField))));
|
||||
|
||||
DBObject dbo = mapper.getMappedObject(query.getQueryObject(), context.getPersistentEntity(Foo.class));
|
||||
|
||||
assertThat(dbo, isBsonObject().containing("my_items.$elemMatch.$and",
|
||||
new BasicDbListBuilder().add(new BasicDBObject("fancy_custom_name", embeddedClass.customizedField)).get()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-647
|
||||
*/
|
||||
@@ -792,8 +817,7 @@ public class QueryMapperUnitTests {
|
||||
}
|
||||
|
||||
/**
|
||||
* <<<<<<< HEAD
|
||||
*
|
||||
*
|
||||
* @see DATAMONGO-1269
|
||||
*/
|
||||
@Test
|
||||
@@ -859,10 +883,15 @@ public class QueryMapperUnitTests {
|
||||
public class Foo {
|
||||
@Id private ObjectId id;
|
||||
EmbeddedClass embedded;
|
||||
|
||||
@Field("my_items")
|
||||
List<EmbeddedClass> listOfItems;
|
||||
}
|
||||
|
||||
public class EmbeddedClass {
|
||||
public String id;
|
||||
|
||||
@Field("fancy_custom_name") public String customizedField;
|
||||
}
|
||||
|
||||
class IdWrapper {
|
||||
|
||||
@@ -887,6 +887,50 @@ public class UpdateMapperUnitTests {
|
||||
assertThat($set.get("primIntValue"), Is.<Object> is(10));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1423
|
||||
*/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void mappingShouldConsiderCustomConvertersForEnumMapKeys() {
|
||||
|
||||
CustomConversions conversions = new CustomConversions(
|
||||
Arrays.asList(AllocationToStringConverter.INSTANCE, StringToAllocationConverter.INSTANCE));
|
||||
|
||||
MongoMappingContext mappingContext = new MongoMappingContext();
|
||||
mappingContext.setSimpleTypeHolder(conversions.getSimpleTypeHolder());
|
||||
mappingContext.afterPropertiesSet();
|
||||
|
||||
MappingMongoConverter converter = new MappingMongoConverter(mock(DbRefResolver.class), mappingContext);
|
||||
converter.setCustomConversions(conversions);
|
||||
converter.afterPropertiesSet();
|
||||
|
||||
UpdateMapper mapper = new UpdateMapper(converter);
|
||||
|
||||
Update update = new Update().set("enumAsMapKey", Collections.singletonMap(Allocation.AVAILABLE, 100));
|
||||
DBObject result = mapper.getMappedObject(update.getUpdateObject(),
|
||||
mappingContext.getPersistentEntity(ClassWithEnum.class));
|
||||
|
||||
assertThat(result, isBsonObject().containing("$set.enumAsMapKey.V", 100));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1486
|
||||
*/
|
||||
@Test
|
||||
public void mappingShouldConvertMapKeysToString() {
|
||||
|
||||
Update update = new Update().set("map", Collections.singletonMap(25, "#StarTrek50"));
|
||||
DBObject mappedUpdate = mapper.getMappedObject(update.getUpdateObject(),
|
||||
context.getPersistentEntity(EntityWithObjectMap.class));
|
||||
|
||||
DBObject mapToSet = getAsDBObject(getAsDBObject(mappedUpdate, "$set"), "map");
|
||||
|
||||
for (Object key : mapToSet.keySet()) {
|
||||
assertThat(key, is(instanceOf(String.class)));
|
||||
}
|
||||
}
|
||||
|
||||
static class DomainTypeWrappingConcreteyTypeHavingListOfInterfaceTypeAttributes {
|
||||
ListModelWrapper concreteTypeWithListAttributeOfInterfaceType;
|
||||
}
|
||||
@@ -1113,6 +1157,7 @@ public class UpdateMapperUnitTests {
|
||||
static class ClassWithEnum {
|
||||
|
||||
Allocation allocation;
|
||||
Map<Allocation, String> enumAsMapKey;
|
||||
|
||||
static enum Allocation {
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2015 the original author or authors.
|
||||
* Copyright 2015-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -29,6 +29,7 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.annotation.PersistenceConstructor;
|
||||
import org.springframework.data.geo.GeoResults;
|
||||
@@ -36,6 +37,7 @@ import org.springframework.data.geo.Metric;
|
||||
import org.springframework.data.geo.Metrics;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
|
||||
import org.springframework.data.mongodb.core.CollectionCallback;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.index.GeoSpatialIndexType;
|
||||
import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
|
||||
@@ -43,11 +45,15 @@ import org.springframework.data.mongodb.core.index.GeospatialIndex;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
import org.springframework.data.mongodb.core.query.NearQuery;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.test.util.BasicDbListBuilder;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBCollection;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.MongoException;
|
||||
import com.mongodb.WriteConcern;
|
||||
|
||||
/**
|
||||
@@ -317,6 +323,66 @@ public class GeoJsonTests {
|
||||
assertThat(venues.size(), is(2));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1453
|
||||
*/
|
||||
@Test
|
||||
public void shouldConvertPointRepresentationCorrectlyWhenSourceCoordinatesUsesInteger() {
|
||||
|
||||
this.template.execute(template.getCollectionName(DocumentWithPropertyUsingGeoJsonType.class),
|
||||
new CollectionCallback<Object>() {
|
||||
|
||||
@Override
|
||||
public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
|
||||
|
||||
BasicDBObject pointRepresentation = new BasicDBObject();
|
||||
pointRepresentation.put("type", "Point");
|
||||
pointRepresentation.put("coordinates", new BasicDbListBuilder().add(0).add(0).get());
|
||||
|
||||
BasicDBObject document = new BasicDBObject();
|
||||
document.append("_id", "datamongo-1453");
|
||||
document.append("geoJsonPoint", pointRepresentation);
|
||||
|
||||
return collection.save(document);
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(template.findOne(query(where("id").is("datamongo-1453")),
|
||||
DocumentWithPropertyUsingGeoJsonType.class).geoJsonPoint, is(equalTo(new GeoJsonPoint(0D, 0D))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1453
|
||||
*/
|
||||
@Test
|
||||
public void shouldConvertLineStringRepresentationCorrectlyWhenSourceCoordinatesUsesInteger() {
|
||||
|
||||
this.template.execute(template.getCollectionName(DocumentWithPropertyUsingGeoJsonType.class),
|
||||
new CollectionCallback<Object>() {
|
||||
|
||||
@Override
|
||||
public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
|
||||
|
||||
BasicDBObject lineStringRepresentation = new BasicDBObject();
|
||||
lineStringRepresentation.put("type", "LineString");
|
||||
lineStringRepresentation.put("coordinates",
|
||||
new BasicDbListBuilder().add(new BasicDbListBuilder().add(0).add(0).get())
|
||||
.add(new BasicDbListBuilder().add(1).add(1).get()).get());
|
||||
|
||||
BasicDBObject document = new BasicDBObject();
|
||||
document.append("_id", "datamongo-1453");
|
||||
document.append("geoJsonLineString", lineStringRepresentation);
|
||||
|
||||
return collection.save(document);
|
||||
}
|
||||
});
|
||||
|
||||
assertThat(
|
||||
template.findOne(query(where("id").is("datamongo-1453")),
|
||||
DocumentWithPropertyUsingGeoJsonType.class).geoJsonLineString,
|
||||
is(equalTo(new GeoJsonLineString(new Point(0D, 0D), new Point(1, 1)))));
|
||||
}
|
||||
|
||||
private void addVenues() {
|
||||
|
||||
template.insert(new Venue2DSphere("Penn Station", -73.99408, 40.75057));
|
||||
|
||||
@@ -86,8 +86,10 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
|
||||
dave = new Person("Dave", "Matthews", 42);
|
||||
oliver = new Person("Oliver August", "Matthews", 4);
|
||||
carter = new Person("Carter", "Beauford", 49);
|
||||
carter.setSkills(Arrays.asList("Drums", "percussion", "vocals"));
|
||||
Thread.sleep(10);
|
||||
boyd = new Person("Boyd", "Tinsley", 45);
|
||||
boyd.setSkills(Arrays.asList("Violin", "Electric Violin", "Viola", "Mandolin", "Vocals", "Guitar"));
|
||||
stefan = new Person("Stefan", "Lessard", 34);
|
||||
leroi = new Person("Leroi", "Moore", 41);
|
||||
|
||||
@@ -1261,4 +1263,37 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
|
||||
assertThat(result.size(), is(2));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1425
|
||||
*/
|
||||
@Test
|
||||
public void findsPersonsByFirstnameNotContains() throws Exception {
|
||||
|
||||
List<Person> result = repository.findByFirstnameNotContains("Boyd");
|
||||
assertThat(result.size(), is((int) (repository.count() - 1)));
|
||||
assertThat(result, not(hasItem(boyd)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1425
|
||||
*/
|
||||
@Test
|
||||
public void findBySkillsContains() throws Exception {
|
||||
|
||||
List<Person> result = repository.findBySkillsContains(Arrays.asList("Drums"));
|
||||
assertThat(result.size(), is(1));
|
||||
assertThat(result, hasItem(carter));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1425
|
||||
*/
|
||||
@Test
|
||||
public void findBySkillsNotContains() throws Exception {
|
||||
|
||||
List<Person> result = repository.findBySkillsNotContains(Arrays.asList("Drums"));
|
||||
assertThat(result.size(), is((int) (repository.count() - 1)));
|
||||
assertThat(result, not(hasItem(carter)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -89,8 +89,14 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
*/
|
||||
List<Person> findByFirstnameLike(String firstname);
|
||||
|
||||
List<Person> findByFirstnameNotContains(String firstname);
|
||||
|
||||
List<Person> findByFirstnameLikeOrderByLastnameAsc(String firstname, Sort sort);
|
||||
|
||||
List<Person> findBySkillsContains(List<String> skills);
|
||||
|
||||
List<Person> findBySkillsNotContains(List<String> skills);
|
||||
|
||||
@Query("{'age' : { '$lt' : ?0 } }")
|
||||
List<Person> findByAgeLessThan(int age, Sort sort);
|
||||
|
||||
@@ -309,7 +315,8 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
* @see DATAMONGO-745
|
||||
*/
|
||||
@Query("{lastname:?0, address.street:{$in:?1}}")
|
||||
Page<Person> findByCustomQueryLastnameAndAddressStreetInList(String lastname, List<String> streetNames, Pageable page);
|
||||
Page<Person> findByCustomQueryLastnameAndAddressStreetInList(String lastname, List<String> streetNames,
|
||||
Pageable page);
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-950
|
||||
@@ -334,19 +341,19 @@ public interface PersonRepository extends MongoRepository<Person, String>, Query
|
||||
*/
|
||||
@Query("{ firstname : { $in : ?0 }}")
|
||||
Stream<Person> findByCustomQueryWithStreamingCursorByFirstnames(List<String> firstnames);
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-990
|
||||
*/
|
||||
@Query("{ firstname : ?#{[0]}}")
|
||||
List<Person> findWithSpelByFirstnameForSpELExpressionWithParameterIndexOnly(String firstname);
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-990
|
||||
*/
|
||||
@Query("{ firstname : ?#{[0]}, email: ?#{principal.email} }")
|
||||
List<Person> findWithSpelByFirstnameAndCurrentUserWithCustomQuery(String firstname);
|
||||
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-990
|
||||
*/
|
||||
|
||||
@@ -454,6 +454,7 @@ public class MongoQueryCreatorUnitTests {
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1075
|
||||
* @see DATAMONGO-1425
|
||||
*/
|
||||
@Test
|
||||
public void shouldCreateRegexWhenUsingNotContainsOnStringProperty() {
|
||||
@@ -462,7 +463,7 @@ public class MongoQueryCreatorUnitTests {
|
||||
MongoQueryCreator creator = new MongoQueryCreator(tree, getAccessor(converter, "thew"), context);
|
||||
Query query = creator.createQuery();
|
||||
|
||||
assertThat(query, is(query(where("username").regex(".*thew.*").not())));
|
||||
assertThat(query.getQueryObject(), is(query(where("username").not().regex(".*thew.*")).getQueryObject()));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2011-2014 the original author or authors.
|
||||
* Copyright 2011-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,6 +19,8 @@ import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.data.mongodb.core.DBObjectTestUtils.*;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.bson.types.ObjectId;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Before;
|
||||
@@ -26,11 +28,15 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.convert.WritingConverter;
|
||||
import org.springframework.data.mongodb.core.convert.CustomConversions;
|
||||
import org.springframework.data.mongodb.core.convert.DbRefResolver;
|
||||
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverter;
|
||||
import org.springframework.data.mongodb.core.mapping.Field;
|
||||
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
|
||||
import org.springframework.data.mongodb.repository.Person.Sex;
|
||||
import org.springframework.data.mongodb.repository.QAddress;
|
||||
import org.springframework.data.mongodb.repository.QPerson;
|
||||
|
||||
@@ -172,10 +178,52 @@ public class SpringDataMongodbSerializerUnitTests {
|
||||
assertThat($in, Matchers.<Object> arrayContaining(firstId, secondId));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-1485
|
||||
*/
|
||||
@Test
|
||||
public void takesCustomConversionForEnumsIntoAccount() {
|
||||
|
||||
MongoMappingContext context = new MongoMappingContext();
|
||||
|
||||
MappingMongoConverter converter = new MappingMongoConverter(dbFactory, context);
|
||||
converter.setCustomConversions(new CustomConversions(Collections.singletonList(new SexTypeWriteConverter())));
|
||||
converter.afterPropertiesSet();
|
||||
|
||||
this.converter = converter;
|
||||
this.serializer = new SpringDataMongodbSerializer(this.converter);
|
||||
|
||||
Object mappedPredicate = this.serializer.handle(QPerson.person.sex.eq(Sex.FEMALE));
|
||||
|
||||
assertThat(mappedPredicate, is(instanceOf(DBObject.class)));
|
||||
assertThat(((DBObject) mappedPredicate).get("sex"), is((Object) "f"));
|
||||
}
|
||||
|
||||
class Address {
|
||||
String id;
|
||||
String street;
|
||||
@Field("zip_code") String zipCode;
|
||||
@Field("bar") String[] foo;
|
||||
}
|
||||
|
||||
@WritingConverter
|
||||
public class SexTypeWriteConverter implements Converter<Sex, String> {
|
||||
|
||||
@Override
|
||||
public String convert(Sex source) {
|
||||
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (source) {
|
||||
case MALE:
|
||||
return "m";
|
||||
case FEMALE:
|
||||
return "f";
|
||||
default:
|
||||
throw new IllegalArgumentException("o_O");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
The Spring Data MongoDB project applies core Spring concepts to the development of solutions using the MongoDB document style data store. We provide a "template" as a high-level abstraction for storing and querying documents. You will notice similarities to the JDBC support in the Spring Framework.
|
||||
|
||||
This document is the reference guide for Spring Data - Document Support. It explains Document module concepts and semantics and the syntax for various stores namespaces.
|
||||
This document is the reference guide for Spring Data - Document Support. It explains Document module concepts and semantics and the syntax for various store namespaces.
|
||||
|
||||
This section provides some basic introduction to Spring and Document database. The rest of the document refers only to Spring Data Document features and assumes the user is familiar with document databases such as MongoDB and CouchDB as well as Spring concepts.
|
||||
|
||||
@@ -17,7 +17,7 @@ To learn more about Spring, you can refer to the comprehensive (and sometimes di
|
||||
|
||||
[[get-started:first-steps:nosql]]
|
||||
== Knowing NoSQL and Document databases
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms and patterns (to make things worth even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings]). While some of the principles are common, it is crucial that the user is familiar to some degree with the stores supported by DATADOC. The best way to get acquainted to this solutions is to read their documentation and follow their examples - it usually doesn't take more then 5-10 minutes to go through them and if you are coming from an RDMBS-only background many times these exercises can be an eye opener.
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms and patterns (to make things worse even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings]). While some of the principles are common, it is crucial that the user is familiar to some degree with the stores supported by DATADOC. The best way to get acquainted to this solutions is to read their documentation and follow their examples - it usually doesn't take more then 5-10 minutes to go through them and if you are coming from an RDMBS-only background many times these exercises can be an eye opener.
|
||||
|
||||
The jumping off ground for learning about MongoDB is http://www.mongodb.org/[www.mongodb.org]. Here is a list of other useful resources:
|
||||
|
||||
@@ -56,4 +56,4 @@ Professional, from-the-source support, with guaranteed response time, is availab
|
||||
[[get-started:up-to-date]]
|
||||
=== Following Development
|
||||
|
||||
For information on the Spring Data Mongo source code repository, nightly builds and snapshot artifacts please see the http://projects.spring.io/spring-data-mongodb/[Spring Data Mongo homepage]. You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the Community on http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow]. To follow developer activity look for the mailing list information on the Spring Data Mongo homepage. If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data issue https://jira.spring.io/browse/DATAMONGO[tracker]. To stay up to date with the latest news and announcements in the Spring eco system, subscribe to the Spring Community http://spring.io[Portal]. Lastly, you can follow the SpringSource Data http://spring.io/blog[blog ]or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
For information on the Spring Data Mongo source code repository, nightly builds and snapshot artifacts please see the http://projects.spring.io/spring-data-mongodb/[Spring Data Mongo homepage]. You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the Community on http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow]. To follow developer activity look for the mailing list information on the Spring Data Mongo homepage. If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data issue https://jira.spring.io/browse/DATAMONGO[tracker]. To stay up to date with the latest news and announcements in the Spring eco system, subscribe to the Spring Community http://spring.io[Portal]. Lastly, you can follow the Spring http://spring.io/blog[blog ]or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
|
||||
@@ -12,25 +12,25 @@ NOTE: `SimpleMongoConverter` has been deprecated in Spring Data MongoDB M3 as al
|
||||
|
||||
`MongoMappingConverter` has a few conventions for mapping objects to documents when no additional mapping metadata is provided. The conventions are:
|
||||
|
||||
* The short Java class name is mapped to the collection name in the following manner. The class '`com.bigbank.SavingsAccount`' maps to '`savingsAccount`' collection name.
|
||||
* The short Java class name is mapped to the collection name in the following manner. The class `com.bigbank.SavingsAccount` maps to `savingsAccount` collection name.
|
||||
* All nested objects are stored as nested objects in the document and *not* as DBRefs
|
||||
* The converter will use any Spring Converters registered with it to override the default mapping of object properties to document field/values.
|
||||
* The fields of an object are used to convert to and from fields in the document. Public JavaBean properties are not used.
|
||||
* You can have a single non-zero argument constructor whose constructor argument names match top level field names of document, that constructor will be used. Otherwise the zero arg constructor will be used. if there is more than one non-zero argument constructor an exception will be thrown.
|
||||
|
||||
[[mapping.conventions.id-field]]
|
||||
=== How the '_id' field is handled in the mapping layer
|
||||
=== How the `_id` field is handled in the mapping layer
|
||||
|
||||
MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. The "_id" field can be of any type the, other than arrays, so long as it is unique. The driver naturally supports all primitive types and Dates. When using the `MongoMappingConverter` there are certain rules that govern how properties from the Java class is mapped to this '_id' field.
|
||||
MongoDB requires that you have an `_id` field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. The "_id" field can be of any type the, other than arrays, so long as it is unique. The driver naturally supports all primitive types and Dates. When using the `MongoMappingConverter` there are certain rules that govern how properties from the Java class is mapped to this `_id` field.
|
||||
|
||||
The following outlines what field will be mapped to the '_id' document field:
|
||||
The following outlines what field will be mapped to the `_id` document field:
|
||||
|
||||
* A field annotated with `@Id` (`org.springframework.data.annotation.Id`) will be mapped to the '_id' field.
|
||||
* A field without an annotation but named 'id' will be mapped to the '_id' field.
|
||||
* The default field name for identifiers is '_id' and can be customized via the `@Field` annotation.
|
||||
* A field annotated with `@Id` (`org.springframework.data.annotation.Id`) will be mapped to the `_id` field.
|
||||
* A field without an annotation but named `id` will be mapped to the `_id` field.
|
||||
* The default field name for identifiers is `_id` and can be customized via the `@Field` annotation.
|
||||
|
||||
[cols="1,2", options="header"]
|
||||
.Examples for the translation of '_id'-field definitions
|
||||
.Examples for the translation of `_id` field definitions
|
||||
|===
|
||||
| Field definition
|
||||
| Resulting Id-Fieldname in MongoDB
|
||||
@@ -41,24 +41,208 @@ The following outlines what field will be mapped to the '_id' document field:
|
||||
| `@Field` `String` id
|
||||
| `_id`
|
||||
|
||||
| `@Field('x')` `String` id
|
||||
| `@Field("x")` `String` id
|
||||
| `x`
|
||||
|
||||
| `@Id` `String` x
|
||||
| `_id`
|
||||
|
||||
| `@Field('x')` `@Id` `String` x
|
||||
| `@Field("x")` `@Id` `String` x
|
||||
| `_id`
|
||||
|===
|
||||
|
||||
The following outlines what type conversion, if any, will be done on the property mapped to the _id document field.
|
||||
|
||||
* If a field named 'id' is declared as a String or BigInteger in the Java class it will be converted to and stored as an ObjectId if possible. ObjectId as a field type is also valid. If you specify a value for 'id' in your application, the conversion to an ObjectId is detected to the MongoDBdriver. If the specified 'id' value cannot be converted to an ObjectId, then the value will be stored as is in the document's _id field.
|
||||
* If a field named ' id' id field is not declared as a String, BigInteger, or ObjectID in the Java class then you should assign it a value in your application so it can be stored 'as-is' in the document's _id field.
|
||||
* If no field named 'id' 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.
|
||||
* If a field named `id` is declared as a String or BigInteger in the Java class it will be converted to and stored as an ObjectId if possible. ObjectId as a field type is also valid. If you specify a value for `id` in your application, the conversion to an ObjectId is detected to the MongoDBdriver. If the specified `id` value cannot be converted to an ObjectId, then the value will be stored as is in the document's _id field.
|
||||
* If a field named `id` id field is not declared as a String, BigInteger, or ObjectID in the Java class then you should assign it a value in your application so it can be stored 'as-is' in the document's _id field.
|
||||
* If no field named `id` 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 `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 and types used in your queries will be able to match what is in your domain classes.
|
||||
|
||||
[[mapping-conversion]]
|
||||
== Data mapping and type conversion
|
||||
|
||||
This section explain how types are mapped to a MongoDB representation and vice versa. Spring Data MongoDB supports all types that can be represented as BSON, MongoDB's internal document format.
|
||||
In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion, see <<mapping-explicit-converters>> for further details.
|
||||
|
||||
[cols="3,1,6", options="header"]
|
||||
.Type
|
||||
|===
|
||||
| Type
|
||||
| Type conversion
|
||||
| Sample
|
||||
|
||||
| `String`
|
||||
| native
|
||||
| `{"firstname" : "Dave"}`
|
||||
|
||||
| `double`, `Double`, `float`, `Float`
|
||||
| native
|
||||
| `{"weight" : 42.5}`
|
||||
|
||||
| `int`, `Integer`, `short`, `Short`
|
||||
| native +
|
||||
32-bit integer
|
||||
| `{"height" : 42}`
|
||||
|
||||
| `long`, `Long`
|
||||
| native +
|
||||
64-bit integer
|
||||
| `{"height" : 42}`
|
||||
|
||||
| `Date`, `Timestamp`
|
||||
| native
|
||||
| `{"date" : ISODate("2019-11-12T23:00:00.809Z")}`
|
||||
|
||||
| `byte[]`
|
||||
| native
|
||||
| `{"bin" : { "$binary" : "AQIDBA==", "$type" : "00" }}`
|
||||
|
||||
| `java.util.UUID` (Legacy UUID)
|
||||
| native
|
||||
| `{"uuid" : { "$binary" : "MEaf1CFQ6lSphaa3b9AtlA==", "$type" : "03" }}`
|
||||
|
||||
| `Date`
|
||||
| native
|
||||
| `{"date" : ISODate("2019-11-12T23:00:00.809Z")}`
|
||||
|
||||
| `ObjectId`
|
||||
| native
|
||||
| `{"_id" : ObjectId("5707a2690364aba3136ab870")}`
|
||||
|
||||
| Array, `List`, `BasicDBList`
|
||||
| native
|
||||
| `{"cookies" : [ … ]}`
|
||||
|
||||
| `boolean`, `Boolean`
|
||||
| native
|
||||
| `{"active" : true}`
|
||||
|
||||
| `null`
|
||||
| native
|
||||
| `{"value" : null}`
|
||||
|
||||
| `DBObject`
|
||||
| native
|
||||
| `{"value" : { … }}`
|
||||
|
||||
| `AtomicInteger` +
|
||||
calling `get()` before the actual conversion
|
||||
| converter +
|
||||
32-bit integer
|
||||
| `{"value" : "741" }`
|
||||
|
||||
| `AtomicLong` +
|
||||
calling `get()` before the actual conversion
|
||||
| converter +
|
||||
64-bit integer
|
||||
| `{"value" : "741" }`
|
||||
|
||||
| `BigInteger`
|
||||
| converter +
|
||||
`String`
|
||||
| `{"value" : "741" }`
|
||||
|
||||
| `BigDecimal`
|
||||
| converter +
|
||||
`String`
|
||||
| `{"value" : "741.99" }`
|
||||
|
||||
| `URL`
|
||||
| converter
|
||||
| `{"website" : "http://projects.spring.io/spring-data-mongodb/" }`
|
||||
|
||||
| `Locale`
|
||||
| converter
|
||||
| `{"locale : "en_US" }`
|
||||
|
||||
| `char`, `Character`
|
||||
| converter
|
||||
| `{"char" : "a" }`
|
||||
|
||||
| `NamedMongoScript`
|
||||
| converter +
|
||||
`Code`
|
||||
| `{"_id" : "script name", value: (some javascript code)`}
|
||||
|
||||
| `java.util.Currency`
|
||||
| converter
|
||||
| `{"currencyCode" : "EUR"}`
|
||||
|
||||
| `LocalDate` +
|
||||
(Joda, Java 8, JSR310-BackPort)
|
||||
| converter
|
||||
| `{"date" : ISODate("2019-11-12T00:00:00.000Z")}`
|
||||
|
||||
| `LocalDateTime`, `LocalTime`, `Instant` +
|
||||
(Joda, Java 8, JSR310-BackPort)
|
||||
| converter
|
||||
| `{"date" : ISODate("2019-11-12T23:00:00.809Z")}`
|
||||
|
||||
| `DateTime` (Joda)
|
||||
| converter
|
||||
| `{"date" : ISODate("2019-11-12T23:00:00.809Z")}`
|
||||
|
||||
| `DateMidnight` (Joda)
|
||||
| converter
|
||||
| `{"date" : ISODate("2019-11-12T00:00:00.000Z")}`
|
||||
|
||||
| `ZoneId` (Java 8, JSR310-BackPort)
|
||||
| converter
|
||||
| `{"zoneId" : "ECT - Europe/Paris"}`
|
||||
|
||||
| `Box`
|
||||
| converter
|
||||
| `{"box" : { "first" : { "x" : 1.0 , "y" : 2.0} , "second" : { "x" : 3.0 , "y" : 4.0}}`
|
||||
|
||||
| `Polygon`
|
||||
| converter
|
||||
| `{"polygon" : { "points" : [ { "x" : 1.0 , "y" : 2.0} , { "x" : 3.0 , "y" : 4.0} , { "x" : 4.0 , "y" : 5.0}]}}`
|
||||
|
||||
| `Circle`
|
||||
| converter
|
||||
| `{"circle" : { "center" : { "x" : 1.0 , "y" : 2.0} , "radius" : 3.0 , "metric" : "NEUTRAL"}}`
|
||||
|
||||
| `Point`
|
||||
| converter
|
||||
| `{"point" : { "x" : 1.0 , "y" : 2.0}}`
|
||||
|
||||
| `GeoJsonPoint`
|
||||
| converter
|
||||
| `{"point" : { "type" : "Point" , "coordinates" : [3.0 , 4.0] }}`
|
||||
|
||||
| `GeoJsonMultiPoint`
|
||||
| converter
|
||||
| `{"geoJsonLineString" : {"type":"MultiPoint", "coordinates": [ [ 0 , 0 ], [ 0 , 1 ], [ 1 , 1 ] ] }}`
|
||||
|
||||
| `Sphere`
|
||||
| converter
|
||||
| `{"sphere" : { "center" : { "x" : 1.0 , "y" : 2.0} , "radius" : 3.0 , "metric" : "NEUTRAL"}}`
|
||||
|
||||
| `GeoJsonPolygon`
|
||||
| converter
|
||||
| `{"polygon" : { "type" : "Polygon", "coordinates" : [[ [ 0 , 0 ], [ 3 , 6 ], [ 6 , 1 ], [ 0 , 0 ] ]] }}`
|
||||
|
||||
| `GeoJsonMultiPolygon`
|
||||
| converter
|
||||
| `{"geoJsonMultiPolygon" : { "type" : "MultiPolygon", "coordinates" : [
|
||||
[ [ [ -73.958 , 40.8003 ] , [ -73.9498 , 40.7968 ] ] ],
|
||||
[ [ [ -73.973 , 40.7648 ] , [ -73.9588 , 40.8003 ] ] ]
|
||||
] }}`
|
||||
|
||||
| `GeoJsonLineString`
|
||||
| converter
|
||||
| `{ "geoJsonLineString" : { "type" : "LineString", "coordinates" : [ [ 40 , 5 ], [ 41 , 6 ] ] }}`
|
||||
|
||||
| `GeoJsonMultiLineString`
|
||||
| converter
|
||||
| `{"geoJsonLineString" : { "type" : "MultiLineString", coordinates: [
|
||||
[ [ -73.97162 , 40.78205 ], [ -73.96374 , 40.77715 ] ],
|
||||
[ [ -73.97880 , 40.77247 ], [ -73.97036 , 40.76811 ] ]
|
||||
] }}`
|
||||
|===
|
||||
|
||||
|
||||
[[mapping-configuration]]
|
||||
== Mapping Configuration
|
||||
|
||||
@@ -108,11 +292,11 @@ public class GeoSpatialAppConfig extends AbstractMongoConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.Mongo` as well as provide a database name. `AbstractMongoConfiguration` also has a method you can override named '`getMappingBasePackage`' which tells the converter where to scan for classes annotated with the `@org.springframework.data.mongodb.core.mapping.Document` annotation.
|
||||
`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.Mongo` as well as provide a database name. `AbstractMongoConfiguration` also has a method you can override named `getMappingBasePackage(…)` which tells the converter where to scan for classes annotated with the `@Document` annotation.
|
||||
|
||||
You can add additional converters to the converter by overriding the method afterMappingMongoConverterCreation. Also shown in the above example is a `LoggingEventListener` which logs `MongoMappingEvent`s that are posted onto Spring's `ApplicationContextEvent` infrastructure.
|
||||
You can add additional converters to the converter by overriding the method afterMappingMongoConverterCreation. Also shown in the above example is a `LoggingEventListener` which logs `MongoMappingEvent` s that are posted onto Spring's `ApplicationContextEvent` infrastructure.
|
||||
|
||||
NOTE: AbstractMongoConfiguration will create a MongoTemplate instance and registered with the container under the name 'mongoTemplate'.
|
||||
NOTE: AbstractMongoConfiguration will create a MongoTemplate instance and registered with the container under the name `mongoTemplate`.
|
||||
|
||||
You can also override the method `UserCredentials getUserCredentials()` to provide the username and password information to connect to the database.
|
||||
|
||||
@@ -165,7 +349,7 @@ The `base-package` property tells it where to scan for classes annotated with th
|
||||
[[mapping-usage]]
|
||||
== Metadata based Mapping
|
||||
|
||||
To take full advantage of the object mapping functionality inside the Spring Data/MongoDB support, you should annotate your mapped objects with the `@org.springframework.data.mongodb.core.mapping.Document` annotation. Although it is not necessary for the mapping framework to have this annotation (your POJOs will be mapped correctly, even without any annotations), it allows the classpath scanner to find and pre-process your domain objects to extract the necessary metadata. If you don't use this annotation, your application will take a slight performance hit the first time you store a domain object because the mapping framework needs to build up its internal metadata model so it knows about the properties of your domain object and how to persist them.
|
||||
To take full advantage of the object mapping functionality inside the Spring Data/MongoDB support, you should annotate your mapped objects with the `@Document` annotation. Although it is not necessary for the mapping framework to have this annotation (your POJOs will be mapped correctly, even without any annotations), it allows the classpath scanner to find and pre-process your domain objects to extract the necessary metadata. If you don't use this annotation, your application will take a slight performance hit the first time you store a domain object because the mapping framework needs to build up its internal metadata model so it knows about the properties of your domain object and how to persist them.
|
||||
|
||||
.Example domain object
|
||||
====
|
||||
@@ -271,7 +455,7 @@ public class Person<T extends Address> {
|
||||
return ssn;
|
||||
}
|
||||
|
||||
// other getters/setters ommitted
|
||||
// other getters/setters omitted
|
||||
----
|
||||
|
||||
[[mapping-custom-object-construction]]
|
||||
@@ -281,7 +465,7 @@ The mapping subsystem allows the customization of the object construction by ann
|
||||
|
||||
* If a parameter is annotated with the `@Value` annotation, the given expression is evaluated and the result is used as the parameter value.
|
||||
* If the Java type has a property whose name matches the given field of the input document, then it's property information is used to select the appropriate constructor parameter to pass the input field value to. This works only if the parameter name information is present in the java `.class` files which can be achieved by compiling the source with debug information or using the new `-parameters` command-line switch for javac in Java 8.
|
||||
* Otherwise an `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
|
||||
* Otherwise a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -313,7 +497,7 @@ Additional examples for using the `@PersistenceConstructor` annotation can be fo
|
||||
[[mapping-usage-indexes.compound-index]]
|
||||
=== Compound Indexes
|
||||
|
||||
Compound indexes are also supported. They are defined at the class level, rather than on indidividual properties.
|
||||
Compound indexes are also supported. They are defined at the class level, rather than on individual properties.
|
||||
|
||||
NOTE: Compound indexes are very important to improve the performance of queries that involve criteria on multiple fields
|
||||
|
||||
@@ -346,7 +530,7 @@ public class Person {
|
||||
|
||||
NOTE: The text index feature is disabled by default for mongodb v.2.4.
|
||||
|
||||
Creating a text index allows to accumulate several fields into a searchable full text index. It is only possible to have one text index per collection so all fields marked with `@TextIndexed` are combined into this index. Properties can be weighted to influence document score for ranking results. The default language for the text index is english, to change the default language set `@Document(language="spanish")` to any language you want. Using a property called `language` or `@Language` allows to define a language override on a per document base.
|
||||
Creating a text index allows accumulating several fields into a searchable full text index. It is only possible to have one text index per collection so all fields marked with `@TextIndexed` are combined into this index. Properties can be weighted to influence document score for ranking results. The default language for the text index is english, to change the default language set `@Document(language="spanish")` to any language you want. Using a property called `language` or `@Language` allows to define a language override on a per document base.
|
||||
|
||||
.Example Text Index Usage
|
||||
====
|
||||
@@ -401,7 +585,7 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
There's no need to use something like `@OneToMany` because the mapping framework sees that you're wanting a one-to-many relationship because there is a List of objects. When the object is stored in MongoDB, there will be a list of DBRefs rather than the `Account` objects themselves.
|
||||
There's no need to use something like `@OneToMany` because the mapping framework sees that you want a one-to-many relationship because there is a List of objects. When the object is stored in MongoDB, there will be a list of DBRefs rather than the `Account` objects themselves.
|
||||
|
||||
IMPORTANT: The mapping framework does not handle cascading saves. If you change an `Account` object that is referenced by a `Person` object, you must save the Account object separately. Calling `save` on the `Person` object will not automatically save the `Account` objects in the property `accounts`.
|
||||
|
||||
@@ -415,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 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.
|
||||
|
||||
To selectively handle the conversion yourself, register one or more one or more `org.springframework.core.convert.converter.Converter` instances with the MongoConverter.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
We have a quite simple domain object here. Note that it has a property named `id` of type`ObjectId`. The default serialization mechanism used in `MongoTemplate` (which is backing the repository support) regards properties named id as document id. Currently we support`String`, `ObjectId` and `BigInteger` as id-types.
|
||||
We have a quite simple domain object here. Note that it has a property named `id` of type `ObjectId`. The default serialization mechanism used in `MongoTemplate` (which is backing the repository support) regards properties named id as document id. Currently we support `String`, `ObjectId` and `BigInteger` as id-types.
|
||||
|
||||
.Basic repository interface to persist Person entities
|
||||
====
|
||||
@@ -99,7 +99,7 @@ class ApplicationConfig extends AbstractMongoConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
As our domain repository extends `PagingAndSortingRepository` it provides you with CRUD operations as well as methods for paginated and sorted access to the entities. Working with the repository instance is just a matter of dependency injecting it into a client. So accessing the second page of `Person`s at a page size of 10 would simply look something like this:
|
||||
As our domain repository extends `PagingAndSortingRepository` it provides you with CRUD operations as well as methods for paginated and sorted access to the entities. Working with the repository instance is just a matter of dependency injecting it into a client. So accessing the second page of `Person` s at a page size of 10 would simply look something like this:
|
||||
|
||||
.Paging access to Person entities
|
||||
====
|
||||
@@ -139,17 +139,17 @@ public interface PersonRepository extends PagingAndSortingRepository<Person, Str
|
||||
Page<Person> findByFirstname(String firstname, Pageable pageable); <2>
|
||||
|
||||
Person findByShippingAddresses(Address address); <3>
|
||||
|
||||
|
||||
Stream<Person> findAllBy(); <4>
|
||||
}
|
||||
----
|
||||
<1> The method shows a query for all people with the given lastname. The query will be derived parsing the method name for constraints which can be concatenated with `And` and `Or`. Thus the method name will result in a query expression of `{"lastname" : lastname}`.
|
||||
<2> Applies pagination to a query. Just equip your method signature with a `Pageable` parameter and let the method return a `Page` instance and we will automatically page the query accordingly.
|
||||
<3> Shows that you can query based on properties which are not a primitive type.
|
||||
<3> Shows that you can query based on properties which are not a primitive type.
|
||||
<4> Uses a Java 8 `Stream` which reads and converts individual elements while iterating the stream.
|
||||
====
|
||||
|
||||
|
||||
|
||||
|
||||
NOTE: Note that for version 1.0 we currently don't support referring to parameters that are mapped as `DBRef` in the domain class.
|
||||
|
||||
@@ -212,10 +212,18 @@ NOTE: Note that for version 1.0 we currently don't support referring to paramete
|
||||
| `findByFirstnameContaining(String name)`
|
||||
| `{"firstname" : name} (name as regex)`
|
||||
|
||||
| `NotContaining` on String
|
||||
| `findByFirstnameNotContaining(String name)`
|
||||
| `{"firstname" : { "$not" : name}} (name as regex)`
|
||||
|
||||
| `Containing` on Collection
|
||||
| `findByAddressesContaining(Address address)`
|
||||
| `{"addresses" : { "$in" : address}}`
|
||||
|
||||
| `NotContaining` on Collection
|
||||
| `findByAddressesNotContaining(Address address)`
|
||||
| `{"addresses" : { "$not" : { "$in" : address}}}`
|
||||
|
||||
| `Regex`
|
||||
| `findByFirstnameRegex(String firstname)`
|
||||
| `{"firstname" : {"$regex" : firstname }}`
|
||||
@@ -264,7 +272,7 @@ NOTE: Note that for version 1.0 we currently don't support referring to paramete
|
||||
[[mongodb.repositories.queries.delete]]
|
||||
=== Repository delete queries
|
||||
|
||||
The above keywords can be used in conjunciton with `delete…By` or `remove…By` to create queries deleting matching documents.
|
||||
The above keywords can be used in conjunction with `delete…By` or `remove…By` to create queries deleting matching documents.
|
||||
|
||||
.`Delete…By` Query
|
||||
====
|
||||
@@ -284,7 +292,7 @@ Using return type `List` will retrieve and return all matching documents before
|
||||
[[mongodb.repositories.queries.geo-spatial]]
|
||||
=== Geo-spatial repository queries
|
||||
|
||||
As you've just seen there are a few keywords triggering geo-spatial operations within a MongoDB query. The `Near` keyword allows some further modification. Let's have look at some examples:
|
||||
As you've just seen there are a few keywords triggering geo-spatial operations within a MongoDB query. The `Near` keyword allows some further modification. Let's have a look at some examples:
|
||||
|
||||
.Advanced `Near` queries
|
||||
====
|
||||
@@ -328,7 +336,7 @@ public interface PersonRepository extends MongoRepository<Person, String>
|
||||
// Metric: {'geoNear' : 'person', 'near' : [x, y], 'maxDistance' : distance,
|
||||
// 'distanceMultiplier' : metric.multiplier, 'spherical' : true }
|
||||
GeoResults<Person> findByLocationNear(Point location, Distance distance);
|
||||
|
||||
|
||||
// Metric: {'geoNear' : 'person', 'near' : [x, y], 'minDistance' : min,
|
||||
// 'maxDistance' : max, 'distanceMultiplier' : metric.multiplier,
|
||||
// 'spherical' : true }
|
||||
@@ -428,9 +436,9 @@ We think you will find this an extremely powerful tool for writing MongoDB queri
|
||||
|
||||
[[mongodb.repositories.queries.full-text]]
|
||||
=== Full-text search queries
|
||||
MongoDBs full text search feature is very store specic and therefore can rather be found on `MongoRepository` than on the more general `CrudRepository`. What we need is a document with a full-text index defined for (Please see section <<mapping-usage-indexes.text-index>> for creating).
|
||||
MongoDBs full text search feature is very store specific and therefore can rather be found on `MongoRepository` than on the more general `CrudRepository`. What we need is a document with a full-text index defined for (Please see section <<mapping-usage-indexes.text-index>> for creating).
|
||||
|
||||
Additional methods on `MongoRepository` take `TextCriteria` as input parameter. In addition to those explicit methods, it is also possible to add a `TextCriteria` derived repository method. The criteria will added as an additional `AND` criteria. Once the entity contains a `@TextScore` annotated property the documents full-text score will be retrieved. Furthermore the `@TextScore` annotated property will also make it possible to sort by the documents score.
|
||||
Additional methods on `MongoRepository` take `TextCriteria` as input parameter. In addition to those explicit methods, it is also possible to add a `TextCriteria` derived repository method. The criteria will be added as an additional `AND` criteria. Once the entity contains a `@TextScore` annotated property the documents full-text score will be retrieved. Furthermore the `@TextScore` annotated property will also make it possible to sort by the documents score.
|
||||
|
||||
[source, java]
|
||||
----
|
||||
@@ -489,7 +497,7 @@ class MongoTemplateProducer {
|
||||
}
|
||||
----
|
||||
|
||||
The Spring Data MongoDB CDI extension will pick up the `MongoTemplate` available as CDI bean and create a proxy for a Spring Data repository whenever an bean of a repository type is requested by the container. Thus obtaining an instance of a Spring Data repository is a matter of declaring an `@Inject`-ed property:
|
||||
The Spring Data MongoDB CDI extension will pick up the `MongoTemplate` available as CDI bean and create a proxy for a Spring Data repository whenever a bean of a repository type is requested by the container. Thus obtaining an instance of a Spring Data repository is a matter of declaring an `@Inject`-ed property:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
|
||||
@@ -12,11 +12,11 @@ The MongoDB support contains a wide range of features which are summarized below
|
||||
* Java based Query, Criteria, and Update DSLs
|
||||
* Automatic implementation of Repository interfaces including support for custom finder methods.
|
||||
* QueryDSL integration to support type-safe queries.
|
||||
* Cross-store persistance - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
|
||||
* Cross-store persistence - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
|
||||
* Log4j log appender
|
||||
* GeoSpatial integration
|
||||
|
||||
For most tasks you will find yourself using `MongoTemplate` or the Repository support that both leverage the rich mapping functionality. MongoTemplate is the place to look for accessing functionality such as incrementing counters or ad-hoc CRUD operations. MongoTemplate also provides callback methods so that it is easy for you to get a hold of the low level API artifacts such as `org.mongo.DB` to communicate directly with MongoDB. The goal with naming conventions on various API artifacts is to copy those in the base MongoDB Java driver so you can easily map your existing knowledge onto the Spring APIs.
|
||||
For most tasks you will find yourself using `MongoTemplate` or the Repository support that both leverage the rich mapping functionality. `MongoTemplate` is the place to look for accessing functionality such as incrementing counters or ad-hoc CRUD operations. `MongoTemplate` also provides callback methods so that it is easy for you to get a hold of the low level API artifacts such as `com.mongo.DB` to communicate directly with MongoDB. The goal with naming conventions on various API artifacts is to copy those in the base MongoDB Java driver so you can easily map your existing knowledge onto the Spring APIs.
|
||||
|
||||
[[mongodb-getting-started]]
|
||||
== Getting Started
|
||||
@@ -51,7 +51,7 @@ Also change the version of Spring in the pom.xml to be
|
||||
<spring.framework.version>{springVersion}</spring.framework.version>
|
||||
----
|
||||
|
||||
You will also need to add the location of the Spring Milestone repository for maven to your pom.xml which is at the same level of your <dependencies/> element
|
||||
You will also need to add the location of the Spring Milestone repository for maven to your `pom.xml` which is at the same level of your `<dependencies/>` element
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -66,11 +66,11 @@ You will also need to add the location of the Spring Milestone repository for ma
|
||||
|
||||
The repository is also http://repo.spring.io/milestone/org/springframework/data/[browseable here].
|
||||
|
||||
You may also want to set the logging level to `DEBUG` to see some additional information, edit the log4j.properties file to have
|
||||
You may also want to set the logging level to `DEBUG` to see some additional information, edit the `log4j.properties` file to have
|
||||
|
||||
[source]
|
||||
----
|
||||
log4j.category.org.springframework.data.document.mongodb=DEBUG
|
||||
log4j.category.org.springframework.data.mongodb=DEBUG
|
||||
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n
|
||||
----
|
||||
|
||||
@@ -155,7 +155,7 @@ Even in this simple example, there are few things to take notice of
|
||||
|
||||
* You can instantiate the central helper class of Spring Mongo, <<mongo-template,`MongoTemplate`>>, using the standard `com.mongodb.Mongo` object and the name of the database to use.
|
||||
* The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See <<mongo.mapping,here>>.).
|
||||
* Conventions are used for handling the id field, converting it to be a ObjectId when stored in the database.
|
||||
* Conventions are used for handling the id field, converting it to be a `ObjectId` when stored in the database.
|
||||
* Mapping conventions can use field access. Notice the Person class has only getters.
|
||||
* If the constructor argument names match the field names of the stored document, they will be used to instantiate the object
|
||||
|
||||
@@ -195,7 +195,7 @@ public class AppConfig {
|
||||
|
||||
This approach allows you to use the standard `com.mongodb.Mongo` API that you may already be used to using but also pollutes the code with the UnknownHostException checked exception. The use of the checked exception is not desirable as Java based bean metadata uses methods as a means to set object dependencies, making the calling code cluttered.
|
||||
|
||||
An alternative is to register an instance of `com.mongodb.Mongo` instance with the container using Spring's `MongoClientFactoryBean`. As compared to instantiating a `com.mongodb.Mongo` instance directly, the FactoryBean approach does not throw a checked exception and has the added advantage of also providing the container with an ExceptionTranslator implementation that translates MongoDB exceptions to exceptions in Spring's portable `DataAccessException` hierarchy for data access classes annoated with the `@Repository` annotation. This hierarchy and use of `@Repository` is described in http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/dao.html[Spring's DAO support features].
|
||||
An alternative is to register an instance of `com.mongodb.Mongo` instance with the container using Spring's `MongoClientFactoryBean`. As compared to instantiating a `com.mongodb.Mongo` instance directly, the FactoryBean approach does not throw a checked exception and has the added advantage of also providing the container with an ExceptionTranslator implementation that translates MongoDB exceptions to exceptions in Spring's portable `DataAccessException` hierarchy for data access classes annotated with the `@Repository` annotation. This hierarchy and use of `@Repository` is described in http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/dao.html[Spring's DAO support features].
|
||||
|
||||
An example of a Java based bean metadata that supports exception translation on `@Repository` annotated classes is shown below:
|
||||
|
||||
@@ -223,7 +223,7 @@ To access the `com.mongodb.Mongo` object created by the `MongoClientFactoryBean`
|
||||
[[mongo.mongo-xml-config]]
|
||||
=== Registering a Mongo instance using XML based metadata
|
||||
|
||||
While you can use Spring's traditional `<beans/>` XML namespace to register an instance of `com.mongodb.Mongo` with the container, the XML can be quite verbose as it is general purpose. XML namespaces are a better alternative to configuring commonly used objects such as the Mongo instance. The mongo namespace alows you to create a Mongo instance server location, replica-sets, and options.
|
||||
While you can use Spring's traditional `<beans/>` XML namespace to register an instance of `com.mongodb.Mongo` with the container, the XML can be quite verbose as it is general purpose. XML namespaces are a better alternative to configuring commonly used objects such as the Mongo instance. The mongo namespace allows you to create a Mongo instance server location, replica-sets, and options.
|
||||
|
||||
To use the Mongo namespace elements you will need to reference the Mongo schema:
|
||||
|
||||
@@ -250,7 +250,7 @@ To use the Mongo namespace elements you will need to reference the Mongo schema:
|
||||
----
|
||||
====
|
||||
|
||||
A more advanced configuration with MongoOptions is shown below (note these are not recommended values)
|
||||
A more advanced configuration with `MongoOptions` is shown below (note these are not recommended values)
|
||||
|
||||
.XML schema to configure a com.mongodb.Mongo object with MongoOptions
|
||||
====
|
||||
@@ -301,9 +301,9 @@ public interface MongoDbFactory {
|
||||
}
|
||||
----
|
||||
|
||||
The following sections show how you can use the container with either Java or the XML based metadata to configure an instance of the `MongoDbFactory` interface. In turn, you can use the `MongoDbFactory` instance to configure MongoTemplate.
|
||||
The following sections show how you can use the container with either Java or the XML based metadata to configure an instance of the `MongoDbFactory` interface. In turn, you can use the `MongoDbFactory` instance to configure `MongoTemplate`.
|
||||
|
||||
The class `org.springframework.data.mongodb.core.SimpleMongoDbFactory` provides implements the MongoDbFactory interface and is created with a standard `com.mongodb.Mongo` instance, the database name and an optional `org.springframework.data.authentication.UserCredentials` constructor argument.
|
||||
The class `org.springframework.data.mongodb.core.SimpleMongoDbFactory` provides implements the `MongoDbFactory` interface and is created with a standard `com.mongodb.Mongo` instance, the database name and an optional `org.springframework.data.authentication.UserCredentials` constructor argument.
|
||||
|
||||
Instead of using the IoC container to create an instance of MongoTemplate, you can just use them in standard Java code as shown below.
|
||||
|
||||
@@ -366,7 +366,7 @@ public class MongoConfiguration {
|
||||
[[mongo.mongo-db-factory-xml]]
|
||||
=== Registering a MongoDbFactory instance using XML based metadata
|
||||
|
||||
The mongo namespace provides a convient way to create a `SimpleMongoDbFactory` as compared to using the`<beans/>` namespace. Simple usage is shown below
|
||||
The mongo namespace provides a convenient way to create a `SimpleMongoDbFactory` as compared to using the `<beans/>` namespace. Simple usage is shown below
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -387,7 +387,7 @@ You can also provide the host and port for the underlying `com.mongodb.Mongo` in
|
||||
password="secret"/>
|
||||
----
|
||||
|
||||
If you need to configure additional options on the `com.mongodb.Mongo` instance that is used to create a `SimpleMongoDbFactory` you can refer to an existing bean using the `mongo-ref` attribute as shown below. To show another common usage pattern, this listing show the use of a property placeholder to parameterise the configuration and creating `MongoTemplate`.
|
||||
If you need to configure additional options on the `com.mongodb.Mongo` instance that is used to create a `SimpleMongoDbFactory` you can refer to an existing bean using the `mongo-ref` attribute as shown below. To show another common usage pattern, this listing shows the use of a property placeholder to parametrise the configuration and creating `MongoTemplate`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -418,30 +418,30 @@ If you need to configure additional options on the `com.mongodb.Mongo` instance
|
||||
[[mongo-template]]
|
||||
== Introduction to MongoTemplate
|
||||
|
||||
The class `MongoTemplate`, located in the package `org.springframework.data.document.mongodb`, is the central class of the Spring's MongoDB support providing a rich feature 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.
|
||||
The class `MongoTemplate`, located in the package `org.springframework.data.mongodb.core`, is the central class of the Spring's MongoDB support providing a rich feature 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.
|
||||
|
||||
NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across multiple instances.
|
||||
|
||||
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 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 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 `DBObject` and there are fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `DBObject` to specify the parameters for those operations.
|
||||
|
||||
NOTE: The preferred way to reference the operations on `MongoTemplate` instance is via its interface `MongoOperations`.
|
||||
|
||||
The default converter implementation used by `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 additional 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 <<mongo.mapping,Mapping chapter>>.
|
||||
|
||||
NOTE: In the M2 release `SimpleMappingConverter`, was the default and this class is now deprecated as its functionality has been subsumed by the MongoMappingConverter.
|
||||
NOTE: 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 MongoDB Java driver into Spring's portable Data Access Exception hierarchy. Refer to the section on <<mongo.exception,exception translation>> for more information.
|
||||
|
||||
While there are many convenience methods on `MongoTemplate` to help you easily perform common tasks if you should need to access the MongoDB driver API directly to access functionality not explicitly exposed by the MongoTemplate you can use one 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 mongo.executioncallback[Execution Callbacks] for more information.
|
||||
|
||||
Now let's look at a examples of how to work with the `MongoTemplate` in the context of the Spring container.
|
||||
Now let's look at an example of how to work with the `MongoTemplate` in the context of the Spring container.
|
||||
|
||||
[[mongo-template.instantiating]]
|
||||
=== Instantiating MongoTemplate
|
||||
|
||||
You can use Java to create and register an instance of MongoTemplate as shown below.
|
||||
You can use Java to create and register an instance of `MongoTemplate` as shown below.
|
||||
|
||||
.Registering a com.mongodb.Mongo object and enabling Spring's exception translation support
|
||||
====
|
||||
@@ -487,7 +487,7 @@ NOTE: The preferred way to reference the operations on `MongoTemplate` instance
|
||||
[[mongo-template.writeresultchecking]]
|
||||
=== WriteResultChecking Policy
|
||||
|
||||
When in development it is very handy to either log or throw an 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 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.
|
||||
When in development it is very handy to either log or throw an 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 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`.
|
||||
|
||||
[[mongo-template.writeconcern]]
|
||||
=== WriteConcern
|
||||
@@ -643,21 +643,21 @@ NOTE: This example is meant to show the use of save, update and remove operation
|
||||
The query syntax used in the example is explained in more detail in the section <<mongo.query,Querying Documents>>.
|
||||
|
||||
[[mongo-template.id-handling]]
|
||||
=== How the '_id' field is handled in the mapping layer
|
||||
=== How the `_id` field is handled in the mapping layer
|
||||
|
||||
MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a `ObjectId` with a generated value. When using the `MongoMappingConverter` there are certain rules that govern how properties from the Java class is mapped to this '_id' field.
|
||||
MongoDB requires that you have an `_id` field for all documents. If you don't provide one the driver will assign a `ObjectId` with a generated value. When using the `MongoMappingConverter` there are certain rules that govern how properties from the Java class is mapped to this `_id` field.
|
||||
|
||||
The following outlines what property will be mapped to the '_id' document field:
|
||||
The following outlines what property will be mapped to the `_id` document field:
|
||||
|
||||
* A property or field annotated with `@Id` (`org.springframework.data.annotation.Id`) will be mapped to the '_id' field.
|
||||
* A property or field without an annotation but named `id` will be mapped to the '_id' field.
|
||||
* A property or field annotated with `@Id` (`org.springframework.data.annotation.Id`) will be mapped to the `_id` field.
|
||||
* 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 MongoDB 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.
|
||||
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 `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 and types used in your queries will be able to match what is in your domain classes.
|
||||
|
||||
@@ -666,7 +666,7 @@ When querying and updating `MongoTemplate` will use the converter to handle conv
|
||||
|
||||
As MongoDB collections can contain documents that represent instances of a variety of types. A great example here is if you store a hierarchy of classes or simply have a class with a property of type `Object`. In the latter case the values held inside that property have to be read in correctly when retrieving the object. Thus we need a mechanism to store type information alongside the actual document.
|
||||
|
||||
To achieve that the `MappingMongoConverter` uses a `MongoTypeMapper` abstraction with `DefaultMongoTypeMapper` as it's main implementation. It's default behaviour is storing the fully qualified classname under `_class` inside the document for the top-level document as well as for every value if it's a complex type and a subtype of the property type declared.
|
||||
To achieve that the `MappingMongoConverter` uses a `MongoTypeMapper` abstraction with `DefaultMongoTypeMapper` as it's main implementation. Its default behavior is storing the fully qualified classname under `_class` inside the document for the top-level document as well as for every value if it's a complex type and a subtype of the property type declared.
|
||||
|
||||
.Type mapping
|
||||
====
|
||||
@@ -769,11 +769,11 @@ 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, DBObject>` and `Converter<DBObject, 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.
|
||||
|
||||
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.
|
||||
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 qualified) of the class. You may also call the save operation with a specific collection name. The collection to store the object can be overridden using mapping metadata.
|
||||
|
||||
When inserting or saving, if the Id property is not set, the assumption is that its value will be auto-generated by the database. As such, for auto-generation of an ObjectId to succeed the type of the Id property/field in your class must be either a `String`, `ObjectId`, or `BigInteger`.
|
||||
|
||||
@@ -815,7 +815,7 @@ There are two ways to manage the collection name that is used for operating on t
|
||||
The MongoDB driver supports inserting a collection of documents in one operation. The methods in the MongoOperations interface that support this functionality are listed below
|
||||
|
||||
* *insert* inserts an object. If there is an existing document with the same id then an error is generated.
|
||||
* *insertAll* takes a `Collection `of objects as the first parameter. This method inspects each object and inserts it to the appropriate collection based on the rules specified above.
|
||||
* *insertAll* takes a `Collection` of objects as the first parameter. This method inspects each object and inserts it to the appropriate collection based on the rules specified above.
|
||||
* *save* saves the object overwriting any object that might exist with the same id.
|
||||
|
||||
[[mongo-template.save-insert.batch]]
|
||||
@@ -823,12 +823,12 @@ The MongoDB driver supports inserting a collection of documents in one operation
|
||||
|
||||
The MongoDB driver supports inserting a collection of documents in one operation. The methods in the MongoOperations interface that support this functionality are listed below
|
||||
|
||||
* *insert*` methods that take a `Collection` as the first argument. This inserts a list of objects in a single batch write to the database.
|
||||
* *insert* methods that take a `Collection` as the first argument. This inserts a list of objects in a single batch write to the database.
|
||||
|
||||
[[mongodb-template-update]]
|
||||
=== Updating documents in a collection
|
||||
|
||||
For updates we can elect to update the first document found using `MongoOperation`'s method `updateFirst` or we can update all documents that were found to match the query using the method `updateMulti`. Here is an example of an update of all SAVINGS accounts where we are adding a one time $50.00 bonus to the balance using the `$inc` operator.
|
||||
For updates we can elect to update the first document found using `MongoOperation` 's method `updateFirst` or we can update all documents that were found to match the query using the method `updateMulti`. Here is an example of an update of all SAVINGS accounts where we are adding a one-time $50.00 bonus to the balance using the `$inc` operator.
|
||||
|
||||
.Updating documents using the MongoTemplate
|
||||
====
|
||||
@@ -921,7 +921,7 @@ p = template.findAndModify(query, update, new FindAndModifyOptions().returnNew(t
|
||||
assertThat(p.getAge(), is(25));
|
||||
----
|
||||
|
||||
The `FindAndModifyOptions` lets you set the options of returnNew, upsert, and remove. An example extending off the previous code snippit is shown below
|
||||
The `FindAndModifyOptions` lets you set the options of returnNew, upsert, and remove. An example extending off the previous code snippet is shown below
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -975,7 +975,7 @@ IMPORTANT: Using MongoDB driver version 3 requires to set the `WriteConcern` to
|
||||
[[mongo.query]]
|
||||
== Querying Documents
|
||||
|
||||
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. If you like to create `Query` instances from a plain JSON String use `BasicQuery`.
|
||||
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 the 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. If you like to create `Query` instances from a plain JSON String use `BasicQuery`.
|
||||
|
||||
.Creating a Query instance from a plain JSON String
|
||||
====
|
||||
@@ -1045,7 +1045,7 @@ There are also methods on the Criteria class for geospatial queries. Here is a l
|
||||
* `Criteria` *within* `(Circle circle)` Creates a geospatial criterion using `$geoWithin $center` operators.
|
||||
* `Criteria` *within* `(Box box)` Creates a geospatial criterion using a `$geoWithin $box` operation.
|
||||
* `Criteria` *withinSphere* `(Circle circle)` Creates a geospatial criterion using `$geoWithin $center` operators.
|
||||
* `Criteria` *near* `(Point point)` Creates a geospatial criterion using a `$near `operation
|
||||
* `Criteria` *near* `(Point point)` Creates a geospatial criterion using a `$near` operation
|
||||
* `Criteria` *nearSphere* `(Point point)` Creates a geospatial criterion using `$nearSphere$center` operations. This is only available for MongoDB 1.7 and higher.
|
||||
* `Criteria` *minDistance* `(double minDistance)` Creates a geospatial criterion using the `$minDistance` operation, for use with $near.
|
||||
* `Criteria` *maxDistance* `(double maxDistance)` Creates a geospatial criterion using the `$maxDistance` operation, for use with $near.
|
||||
@@ -1077,7 +1077,7 @@ The query methods need to specify the target type T that will be returned and th
|
||||
|
||||
MongoDB supports GeoSpatial queries through the use of operators such as `$near`, `$within`, `geoWithin` and `$nearSphere`. Methods specific to geospatial queries are available on the `Criteria` class. There are also a few shape classes, `Box`, `Circle`, and `Point` that are used in conjunction with geospatial related `Criteria` methods.
|
||||
|
||||
To understand how to perform GeoSpatial queries we will use the following Venue class taken from the integration tests.which relies on using the rich `MappingMongoConverter`.
|
||||
To understand how to perform GeoSpatial queries we will use the following Venue class taken from the integration tests which relies on using the rich `MappingMongoConverter`.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -1162,7 +1162,7 @@ List<Venue> venues =
|
||||
template.find(new Query(Criteria.where("location").near(point).minDistance(0.01).maxDistance(100)), Venue.class);
|
||||
----
|
||||
|
||||
To find venues near a `Point` using spherical coordines the following query can be used
|
||||
To find venues near a `Point` using spherical coordinates the following query can be used
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -1188,7 +1188,7 @@ GeoResults<Restaurant> = operations.geoNear(query, Restaurant.class);
|
||||
|
||||
As you can see we use the `NearQuery` builder API to set up a query to return all `Restaurant` instances surrounding the given `Point` by 10 miles maximum. The `Metrics` enum used here actually implements an interface so that other metrics could be plugged into a distance as well. A `Metric` is backed by a multiplier to transform the distance value of the given metric into native distances. The sample shown here would consider the 10 to be miles. Using one of the pre-built in metrics (miles and kilometers) will automatically trigger the spherical flag to be set on the query. If you want to avoid that, simply hand in plain `double` values into `maxDistance(…)`. For more information see the JavaDoc of `NearQuery` and `Distance`.
|
||||
|
||||
The geo near operations return a `GeoResults` wrapper object that encapsulates `GeoResult` instances. The wrapping `GeoResults` allows to access the average distance of all results. A single `GeoResult` object simply carries the entity found plus its distance from the origin.
|
||||
The geo near operations return a `GeoResults` wrapper object that encapsulates `GeoResult` instances. The wrapping `GeoResults` allows accessing the average distance of all results. A single `GeoResult` object simply carries the entity found plus its distance from the origin.
|
||||
|
||||
[[mongo.geo-json]]
|
||||
=== GeoJSON Support
|
||||
@@ -1385,7 +1385,7 @@ Executing this will result in a collection as shown below.
|
||||
{ "_id" : "d", "value" : 1 }
|
||||
----
|
||||
|
||||
Assuming that the map and reduce functions are located in map.js and reduce.js and bundled in your jar so they are available on the classpath, you can execute a map-reduce operation and obtain the results as shown below
|
||||
Assuming that the map and reduce functions are located in `map.js` and `reduce.js` and bundled in your jar so they are available on the classpath, you can execute a map-reduce operation and obtain the results as shown below
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -1463,7 +1463,7 @@ Note that you can specify additional limit and sort values as well on the query
|
||||
[[mongo.server-side-scripts]]
|
||||
== Script Operations
|
||||
|
||||
MongoDB allows to execute JavaScript functions on the server by either directly sending the script or calling a stored one. `ScriptOperations` can be accessed via `MongoTemplate` and provides basic abstraction for `JavaScript` usage.
|
||||
MongoDB allows executing JavaScript functions on the server by either directly sending the script or calling a stored one. `ScriptOperations` can be accessed via `MongoTemplate` and provides basic abstraction for `JavaScript` usage.
|
||||
|
||||
=== Example Usage
|
||||
|
||||
@@ -1486,14 +1486,14 @@ scriptOps.call("echo", "execute script via name"); <3>
|
||||
[[mongo.group]]
|
||||
== Group Operations
|
||||
|
||||
As an alternative to using Map-Reduce to perform data aggregation, you can use the http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group[`group` operation] which feels similar to using SQL's group by query style, so it may feel more approachable vs. using Map-Reduce. Using the group operations does have some limitations, for example it is not supported in a shareded environment and it returns the full result set in a single BSON object, so the result should be small, less than 10,000 keys.
|
||||
As an alternative to using Map-Reduce to perform data aggregation, you can use the http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group[`group` operation] which feels similar to using SQL's group by query style, so it may feel more approachable vs. using Map-Reduce. Using the group operations does have some limitations, for example it is not supported in a shared environment and it returns the full result set in a single BSON object, so the result should be small, less than 10,000 keys.
|
||||
|
||||
Spring provides integration with MongoDB's group operation by providing methods on MongoOperations to simplify the creation and execution of group operations. It can convert the results of the group operation to a POJO and also integrates with Spring's http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/resources.html[Resource abstraction] abstraction. This will let you place your JavaScript files on the file system, classpath, http server or any other Spring Resource implementation and then reference the JavaScript resources via an easy URI style syntax, e.g. 'classpath:reduce.js;. Externalizing JavaScript code in files if often preferable to embedding them as Java strings in your code. Note that you can still pass JavaScript code as Java strings if you prefer.
|
||||
|
||||
[[mongo.group.example]]
|
||||
=== Example Usage
|
||||
|
||||
In order to understand how group operations work the following example is used, which is somewhat artificial. For a more realistic example consult the book 'MongoDB - The definitive guide'. A collection named "group_test_collection" created with the following rows.
|
||||
In order to understand how group operations work the following example is used, which is somewhat artificial. For a more realistic example consult the book 'MongoDB - The definitive guide'. A collection named `group_test_collection` created with the following rows.
|
||||
|
||||
[source]
|
||||
----
|
||||
@@ -1505,7 +1505,7 @@ In order to understand how group operations work the following example is used,
|
||||
{ "_id" : ObjectId("4ec1d25d41421e2015da64f6"), "x" : 3 }
|
||||
----
|
||||
|
||||
We would like to group by the only field in each row, the 'x' field and aggregate the number of times each specific value of 'x' occurs. To do this we need to create an initial document that contains our count variable and also a reduce function which will increment it each time it is encountered. The Java code to execute the group operation is shown below
|
||||
We would like to group by the only field in each row, the `x` field and aggregate the number of times each specific value of `x` occurs. To do this we need to create an initial document that contains our count variable and also a reduce function which will increment it each time it is encountered. The Java code to execute the group operation is shown below
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -1594,7 +1594,7 @@ The Aggregation Framework support in Spring Data MongoDB is based on the followi
|
||||
|
||||
* `Aggregation`
|
||||
+
|
||||
An Aggregation represents a MongoDB `aggregate` operation and holds the description of the aggregation pipline instructions. Aggregations are created by inoking the appropriate `newAggregation(…)` static factory Method of the `Aggregation` class which takes the list of `AggregateOperation` as a parameter next to the optional input class.
|
||||
An Aggregation represents a MongoDB `aggregate` operation and holds the description of the aggregation pipeline instructions. Aggregations are created by invoking the appropriate `newAggregation(…)` static factory Method of the `Aggregation` class which takes the list of `AggregateOperation` as a parameter next to the optional input class.
|
||||
+
|
||||
The actual aggregate operation is executed by the `aggregate` method of the `MongoTemplate` which also takes the desired output class as parameter.
|
||||
+
|
||||
@@ -1664,7 +1664,7 @@ Note that the aggregation operations not listed here are currently not supported
|
||||
[[mongo.aggregation.projection]]
|
||||
=== Projection Expressions
|
||||
|
||||
Projection expressions are used to define the fields that are the outcome of a particular aggregation step. Projection expressions can be defined via the `project` method of the `Aggregate` class either by passing a list of `String`s or an aggregation framework `Fields` object. The projection can be extended with additional fields through a fluent API via the `and(String)` method and aliased via the `as(String)` method.
|
||||
Projection expressions are used to define the fields that are the outcome of a particular aggregation step. Projection expressions can be defined via the `project` method of the `Aggregate` class either by passing a list of `String` 's or an aggregation framework `Fields` object. The projection can be extended with additional fields through a fluent API via the `and(String)` method and aliased via the `as(String)` method.
|
||||
Note that one can also define fields with aliases via the static factory method `Fields.field` of the aggregation framework that can then be used to construct a new `Fields` instance.
|
||||
|
||||
.Projection expression examples
|
||||
@@ -1749,7 +1749,7 @@ List<TagCount> tagCount = results.getMappedResults();
|
||||
* In the forth step we use the `group` operation to define a group for each `"tags"`-value for which we aggregate the occurrence count via the `count` aggregation operator and collect the result in a new field called `"n"`.
|
||||
* As a fifth step we select the field `"n"` and create an alias for the id-field generated from the previous group operation (hence the call to `previousOperation()`) with the name `"tag"`.
|
||||
* As the sixth step we sort the resulting list of tags by their occurrence count in descending order via the `sort` operation.
|
||||
* Finally we call the `aggregate` Method on the MongoTemplate in order to let MongoDB perform the acutal aggregation operation with the created `Aggregation` as an argument.
|
||||
* Finally we call the `aggregate` Method on the MongoTemplate in order to let MongoDB perform the actual aggregation operation with the created `Aggregation` as an argument.
|
||||
|
||||
Note that the input collection is explicitly specified as the `"tags"` parameter to the `aggregate` Method. If the name of the input collection is not specified explicitly, it is derived from the input-class passed as first parameter to the `newAggreation` Method.
|
||||
|
||||
@@ -1808,10 +1808,10 @@ ZipInfoStats firstZipInfoStats = result.getMappedResults().get(0);
|
||||
----
|
||||
|
||||
* The class `ZipInfo` maps the structure of the given input-collection. The class `ZipInfoStats` defines the structure in the desired output format.
|
||||
* As a first step we use the `group` operation to define a group from the input-collection. The grouping criteria is the combination of the fields `"state"` and `"city" `which forms the id structure of the group. We aggregate the value of the `"population"` property from the grouped elements with by using the `sum` operator saving the result in the field `"pop"`.
|
||||
* As a first step we use the `group` operation to define a group from the input-collection. The grouping criteria is the combination of the fields `"state"` and `"city"` which forms the id structure of the group. We aggregate the value of the `"population"` property from the grouped elements with by using the `sum` operator saving the result in the field `"pop"`.
|
||||
* In a second step we use the `sort` operation to sort the intermediate-result by the fields `"pop"`, `"state"` and `"city"` in ascending order, such that the smallest city is at the top and the biggest city is at the bottom of the result. Note that the sorting on "state" and `"city"` is implicitly performed against the group id fields which Spring Data MongoDB took care of.
|
||||
* In the third step we use a `group` operation again to group the intermediate result by `"state"`. Note that `"state"` again implicitly references an group-id field. We select the name and the population count of the biggest and smallest city with calls to the `last(…)` and `first(...)` operator respectively via the `project` operation.
|
||||
* As the forth step we select the `"state"` field from the previous `group` operation. Note that `"state"` again implicitly references an group-id field. As we do not want an implicit generated id to appear, we exclude the id from the previous operation via `and(previousOperation()).exclude()`. As we want to populate the nested `City` structures in our output-class accordingly we have to emit appropriate sub-documents with the nested method.
|
||||
* As the forth step we select the `"state"` field from the previous `group` operation. Note that `"state"` again implicitly references an group-id field. As we do not want an implicitly generated id to appear, we exclude the id from the previous operation via `and(previousOperation()).exclude()`. As we want to populate the nested `City` structures in our output-class accordingly we have to emit appropriate sub-documents with the nested method.
|
||||
* Finally as the fifth step we sort the resulting list of `StateStats` by their state name in ascending order via the `sort` operation.
|
||||
|
||||
Note that we derive the name of the input-collection from the `ZipInfo`-class passed as first parameter to the `newAggregation`-Method.
|
||||
@@ -1923,7 +1923,7 @@ List<DBObject> resultList = result.getMappedResults();
|
||||
|
||||
This example demonstrates the use of complex arithmetic operations derived from SpEL Expressions in the projection operation.
|
||||
|
||||
Note: The additional parameters passed to the `addExpression` Method can be referenced via indexer expressions according to their position. In this example we reference the parameter which is the first parameter of the parameters array via `[0]`. External parameter expressions are replaced with their respective values when the SpEL expression is transformed into a MongoDB aggregation framework expression.
|
||||
Note: The additional parameters passed to the `addExpression` Method can be referenced via indexer expressions according to their position. In this example we reference the parameter which is the first parameter of the parameters array via `[0]`. External parameter expressions are replaced with their respective values when the SpEL expression is transformed into a MongoDB aggregation framework expression.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -1955,7 +1955,7 @@ Note that we can also refer to other fields of the document within the SpEL expr
|
||||
[[mongo.custom-converters]]
|
||||
== 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`.
|
||||
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.
|
||||
|
||||
@@ -1988,7 +1988,7 @@ 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 ot a Person object is shownn below
|
||||
An example implementation of a Converter that converts from a DBObject to a Person object is shown below.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -2005,7 +2005,7 @@ public class PersonReadConverter implements Converter<DBObject, Person> {
|
||||
[[mongo.custom-converters.xml]]
|
||||
=== Registering Spring Converters with the MongoConverter
|
||||
|
||||
The Mongo Spring namespace provides a convenience way to register Spring `Converter`s with the `MappingMongoConverter`. The configuration snippet below shows how to manually register converter beans as well as configuring the wrapping `MappingMongoConverter` into a `MongoTemplate`.
|
||||
The Mongo Spring namespace provides a convenience way to register Spring `Converter` s with the `MappingMongoConverter`. The configuration snippet below shows how to manually register converter beans as well as configuring the wrapping `MappingMongoConverter` into a `MongoTemplate`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -2051,7 +2051,7 @@ class MyConverter implements Converter<Person, String> { … }
|
||||
class MyConverter implements Converter<String, Person> { … }
|
||||
----
|
||||
|
||||
In case you write a `Converter` whose source and target type are native Mongo types there's no way for us to determine whether we should consider it as reading or writing converter. Registering the converter instance as both might lead to unwanted results then. E.g. a `Converter<String, Long>` is ambiguous although it probably does not make sense to try to convert all `String` instances into `Long` instances when writing. To be generally able to force the infrastructure to register a converter for one way only we provide `@ReadingConverter` as well as `@WritingConverter` to be used at the converter implementation.
|
||||
In case you write a `Converter` whose source and target type are native Mongo types there's no way for us to determine whether we should consider it as reading or writing converter. Registering the converter instance as both might lead to unwanted results then. E.g. a `Converter<String, Long>` is ambiguous although it probably does not make sense to try to convert all `String` instances into `Long` instances when writing. To be generally able to force the infrastructure to register a converter for one way only we provide `@ReadingConverter` as well as `@WritingConverter` to be used in the converter implementation.
|
||||
|
||||
[[mongo-template.index-and-collections]]
|
||||
== Index and Collection management
|
||||
@@ -2100,7 +2100,7 @@ mongoTemplate.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location"))
|
||||
[[mongo-template.index-and-collections.access]]
|
||||
=== Accessing index information
|
||||
|
||||
The IndexOperations interface has the method getIndexInfo that returns a list of IndexInfo objects. This contains all the indexes defined on the collectcion. Here is an example that defines an index on the Person class that has age property.
|
||||
The IndexOperations interface has the method getIndexInfo that returns a list of IndexInfo objects. This contains all the indexes defined on the collection. Here is an example that defines an index on the Person class that has age property.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -2151,7 +2151,7 @@ You can also get at the MongoDB driver's `DB.command( )` method using the `execu
|
||||
[[mongodb.mapping-usage.events]]
|
||||
== Lifecycle Events
|
||||
|
||||
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 infastructure 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.
|
||||
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.
|
||||
|
||||
@@ -2203,7 +2203,7 @@ Some of the mappings performed by the `MongoExceptionTranslator` are: com.mongod
|
||||
[[mongo.executioncallback]]
|
||||
== Execution callbacks
|
||||
|
||||
One common design feature of all Spring template classes is that all functionality is routed into one of the templates execute callback methods. This helps ensure that exceptions and any resource management that maybe required are performed consistency. While this was of much greater need in the case of JDBC and JMS than with MongoDB, it still offers a single spot for exception translation and logging to occur. As such, using thexe execute callback is the preferred way to access the MongoDB driver's `DB` and `DBCollection` objects to perform uncommon operations that were not exposed as methods on `MongoTemplate`.
|
||||
One common design feature of all Spring template classes is that all functionality is routed into one of the templates execute callback methods. This helps ensure that exceptions and any resource management that maybe required are performed consistency. While this was of much greater need in the case of JDBC and JMS than with MongoDB, it still offers a single spot for exception translation and logging to occur. As such, using these execute callback is the preferred way to access the MongoDB driver's `DB` and `DBCollection` objects to perform uncommon operations that were not exposed as methods on `MongoTemplate`.
|
||||
|
||||
Here is a list of execute callback methods.
|
||||
|
||||
@@ -2215,7 +2215,7 @@ Here is a list of execute callback methods.
|
||||
|
||||
* `<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* `(DbCallback<T> action) ` Executes the given DbCallback within the same connection to the database so as to ensure consistency in a write heavy environment where you may read the data that you wrote.
|
||||
* `<T> T` *executeInSession* `(DbCallback<T> action)` Executes the given DbCallback within the same connection to the database so as to ensure consistency in a write heavy environment where you may read the data that you wrote.
|
||||
|
||||
Here is an example that uses the `CollectionCallback` to return information about an index
|
||||
|
||||
@@ -2306,7 +2306,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 marshalled 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 `DBObject` 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()`.
|
||||
|
||||
|
||||
@@ -1,6 +1,72 @@
|
||||
Spring Data MongoDB Changelog
|
||||
=============================
|
||||
|
||||
Changes in version 1.9.3.RELEASE (2016-09-20)
|
||||
---------------------------------------------
|
||||
* DATAMONGO-1493 - Typos in reference documentation.
|
||||
* DATAMONGO-1492 - Interface AggregationExpression in package org.springframework.data.mongodb.core.aggregation should be public.
|
||||
* DATAMONGO-1486 - Changes to MappingMongoConverter Result in Class Cast Exception.
|
||||
* DATAMONGO-1485 - Querydsl MongodbSerializer does not take registered converters for Enums into account.
|
||||
* DATAMONGO-1479 - MappingMongoConverter.convertToMongoType causes StackOverflowError for parameterized map value types.
|
||||
* DATAMONGO-1471 - MappingMongoConverter attempts to set null value on potentially primitive identifier.
|
||||
* DATAMONGO-1465 - String arguments passed to DefaultScriptOperations.execute() appear quoted in script.
|
||||
* DATAMONGO-1463 - Upgrade to MongoDB Java driver 2.14.3.
|
||||
* DATAMONGO-1453 - Parse error into GeoJsonPoint if coordinates are "integers".
|
||||
* DATAMONGO-1450 - Release 1.9.3 (Hopper SR3).
|
||||
* DATAMONGO-1406 - Query mapper does not use @Field field name when querying nested fields in combination with nested keywords.
|
||||
|
||||
|
||||
Changes in version 1.10.0.M1 (2016-07-27)
|
||||
-----------------------------------------
|
||||
* DATAMONGO-1464 - Pagination - Optimize out the count query for paging.
|
||||
* DATAMONGO-1463 - Upgrade to MongoDB Java driver 2.14.3.
|
||||
* DATAMONGO-1462 - Integrate version badge from spring.io.
|
||||
* DATAMONGO-1460 - User placeholder property for JSR-303 API.
|
||||
* DATAMONGO-1459 - Add support for any-match mode in query-by-example.
|
||||
* DATAMONGO-1457 - Add support for $slice in projection stage of aggregation.
|
||||
* DATAMONGO-1456 - Add support for $diacriticInsensitivity to text search.
|
||||
* DATAMONGO-1455 - Add support for $caseSensitive to text search.
|
||||
* DATAMONGO-1453 - Parse error into GeoJsonPoint if coordinates are "integers".
|
||||
* DATAMONGO-1449 - Replace legacy for loop with foreach in MappingMongoConverter.
|
||||
* DATAMONGO-1437 - DefaultDbRefResolver swallows cause of non DataAccessException translatable Exception.
|
||||
* DATAMONGO-1431 - Add overload of MongoOperations.stream(…) to take an explicit collection name.
|
||||
* DATAMONGO-1425 - NOT_CONTAINS keyword issues CONTAINS query.
|
||||
* DATAMONGO-1424 - Add support for "notLike" keyword in derived queries.
|
||||
* DATAMONGO-1423 - Nested document update doesn't apply converters on embedded maps.
|
||||
* DATAMONGO-1420 - Update Spring Data MongoDB version in Github readme.
|
||||
* DATAMONGO-1419 - Remove deprecations in AbstractMongoEventListener.
|
||||
* DATAMONGO-1418 - Add support for $out operand for Aggregation.
|
||||
* DATAMONGO-1416 - Standard bootstrap issues warning in converter registration.
|
||||
* DATAMONGO-1412 - Document mapping rules for Java types to MongoDB representation.
|
||||
* DATAMONGO-1411 - Enable MongoDB build on TravisCI.
|
||||
* DATAMONGO-1409 - Release 1.10 M1 (Ingalls).
|
||||
* DATAMONGO-1404 - Add support of $max and $min update operations.
|
||||
* DATAMONGO-1403 - Add maxExecutionTimeMs alias for @Meta(maxExcecutionTime).
|
||||
* DATAMONGO-1399 - Allow adding hole to GeoJson Polygon.
|
||||
* DATAMONGO-1394 - References not handled correctly when using QueryDSL.
|
||||
* DATAMONGO-1391 - Support Mongo 3.2 syntax for $unwind in aggregation.
|
||||
* DATAMONGO-1271 - Provide read lifecycle events when loading DBRefs.
|
||||
* DATAMONGO-1194 - Improve DBRef resolution for collections.
|
||||
* DATAMONGO-832 - Add support for $slice in Update.push.
|
||||
|
||||
|
||||
Changes in version 1.9.2.RELEASE (2016-06-15)
|
||||
---------------------------------------------
|
||||
* DATAMONGO-1449 - Replace legacy for loop with foreach in MappingMongoConverter.
|
||||
* DATAMONGO-1437 - DefaultDbRefResolver swallows cause of non DataAccessException translatable Exception.
|
||||
* DATAMONGO-1425 - NOT_CONTAINS keyword issues CONTAINS query.
|
||||
* DATAMONGO-1423 - Nested document update doesn't apply converters on embedded maps.
|
||||
* DATAMONGO-1416 - Standard bootstrap issues warning in converter registration.
|
||||
* DATAMONGO-1412 - Document mapping rules for Java types to MongoDB representation.
|
||||
* DATAMONGO-1411 - Enable MongoDB build on TravisCI.
|
||||
* DATAMONGO-1410 - Release 1.9.2 (Hopper SR2).
|
||||
|
||||
|
||||
Changes in version 1.9.1.RELEASE (2016-04-06)
|
||||
---------------------------------------------
|
||||
* DATAMONGO-1408 - Release 1.9.1 (Hopper SR1).
|
||||
|
||||
|
||||
Changes in version 1.9.0.RELEASE (2016-04-06)
|
||||
---------------------------------------------
|
||||
* DATAMONGO-1407 - Add pull request template.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Spring Data MongoDB 1.9 GA
|
||||
Spring Data MongoDB 1.9.3
|
||||
Copyright (c) [2010-2015] Pivotal Software, Inc.
|
||||
|
||||
This product is licensed to you under the Apache License, Version 2.0 (the "License").
|
||||
|
||||
Reference in New Issue
Block a user