DATAMONGO-1679 - Adapt to API changes in repository interfaces.

This commit is contained in:
Oliver Gierke
2017-05-03 12:12:57 +02:00
parent 5d8370fa90
commit e3238593ce
30 changed files with 459 additions and 581 deletions

View File

@@ -422,7 +422,7 @@ public class QueryMapper {
return getMappedObject((BasicDBObject) source, entity);
}
if(source instanceof BsonValue) {
if (source instanceof BsonValue) {
return source;
}

View File

@@ -15,13 +15,14 @@
*/
package org.springframework.data.mongodb.core.query;
import lombok.EqualsAndHashCode;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.bson.Document;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* @author Thomas Risberg
@@ -30,6 +31,7 @@ import org.springframework.util.ObjectUtils;
* @author Christoph Strobl
* @author Mark Paluch
*/
@EqualsAndHashCode
public class Field {
private final Map<String, Integer> criteria = new HashMap<String, Integer>();
@@ -83,6 +85,7 @@ public class Field {
public Document getFieldsObject() {
@SuppressWarnings({ "unchecked", "rawtypes" })
Document document = new Document((Map) criteria);
for (Entry<String, Object> entry : slices.entrySet()) {
@@ -99,58 +102,4 @@ public class Field {
return document;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Field)) {
return false;
}
Field that = (Field) object;
if (!this.criteria.equals(that.criteria)) {
return false;
}
if (!this.slices.equals(that.slices)) {
return false;
}
if (!this.elemMatchs.equals(that.elemMatchs)) {
return false;
}
boolean samePositionKey = this.postionKey == null ? that.postionKey == null
: this.postionKey.equals(that.postionKey);
boolean samePositionValue = this.positionValue == that.positionValue;
return samePositionKey && samePositionValue;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = 17;
result += 31 * ObjectUtils.nullSafeHashCode(this.criteria);
result += 31 * ObjectUtils.nullSafeHashCode(this.elemMatchs);
result += 31 * ObjectUtils.nullSafeHashCode(this.slices);
result += 31 * ObjectUtils.nullSafeHashCode(this.postionKey);
result += 31 * ObjectUtils.nullSafeHashCode(this.positionValue);
return result;
}
}

View File

@@ -33,7 +33,6 @@ import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* @author Thomas Risberg
@@ -48,8 +47,8 @@ public class Query {
private final Set<Class<?>> restrictedTypes = new HashSet<Class<?>>();
private final Map<String, CriteriaDefinition> criteria = new LinkedHashMap<String, CriteriaDefinition>();
private Field fieldSpec;
private Sort sort;
private Field fieldSpec = null;
private Sort sort = Sort.unsorted();
private long skip;
private int limit;
private String hint;
@@ -103,9 +102,11 @@ public class Query {
}
public Field fields() {
if (fieldSpec == null) {
if (this.fieldSpec == null) {
this.fieldSpec = new Field();
}
return this.fieldSpec;
}
@@ -170,22 +171,19 @@ public class Query {
*/
public Query with(Sort sort) {
if (sort == null || ObjectUtils.nullSafeEquals(Sort.unsorted(), sort)) {
Assert.notNull(sort, "Sort must not be null!");
if (sort.isUnsorted()) {
return this;
}
for (Order order : sort) {
if (order.isIgnoreCase()) {
throw new IllegalArgumentException(String.format("Given sort contained an Order for %s with ignore case! "
+ "MongoDB does not support sorting ignoreing case currently!", order.getProperty()));
}
}
sort.stream().filter(Order::isIgnoreCase).findFirst().ifPresent(it -> {
if (this.sort == null) {
this.sort = sort;
} else {
this.sort = this.sort.and(sort);
}
throw new IllegalArgumentException(String.format("Given sort contained an Order for %s with ignore case! "
+ "MongoDB does not support sorting ignoring case currently!", it.getProperty()));
});
this.sort = this.sort.and(sort);
return this;
}
@@ -238,15 +236,14 @@ public class Query {
public Document getSortObject() {
if (this.sort == null) {
if (this.sort.isUnsorted()) {
return null;
}
Document document = new Document();
for (org.springframework.data.domain.Sort.Order order : this.sort) {
document.put(order.getProperty(), order.isAscending() ? 1 : -1);
}
this.sort.stream()//
.forEach(order -> document.put(order.getProperty(), order.isAscending() ? 1 : -1));
return document;
}
@@ -440,7 +437,7 @@ public class Query {
boolean criteriaEqual = this.criteria.equals(that.criteria);
boolean fieldsEqual = nullSafeEquals(this.fieldSpec, that.fieldSpec);
boolean sortEqual = nullSafeEquals(this.sort, that.sort);
boolean sortEqual = this.sort.equals(that.sort);
boolean hintEqual = nullSafeEquals(this.hint, that.hint);
boolean skipEqual = this.skip == that.skip;
boolean limitEqual = this.limit == that.limit;

View File

@@ -38,10 +38,10 @@ public interface MongoRepository<T, ID extends Serializable>
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
* @see org.springframework.data.repository.CrudRepository#saveAll(java.lang.Iterable)
*/
@Override
<S extends T> List<S> save(Iterable<S> entites);
<S extends T> List<S> saveAll(Iterable<S> entites);
/*
* (non-Javadoc)
@@ -58,9 +58,9 @@ public interface MongoRepository<T, ID extends Serializable>
List<T> findAll(Sort sort);
/**
* Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use
* the returned instance for further operations as the save operation might have changed the entity instance
* completely. Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
* Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use the
* returned instance for further operations as the save operation might have changed the entity instance completely.
* Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
*
* @param entity must not be {@literal null}.
* @return the saved entity

View File

@@ -15,16 +15,14 @@
*/
package org.springframework.data.mongodb.repository;
import java.io.Serializable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.reactivestreams.Publisher;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.reactive.ReactiveSortingRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Mongo specific {@link org.springframework.data.repository.Repository} interface with reactive support.
@@ -33,12 +31,12 @@ import reactor.core.publisher.Mono;
* @since 2.0
*/
@NoRepositoryBean
public interface ReactiveMongoRepository<T, ID extends Serializable> extends ReactiveSortingRepository<T, ID> {
public interface ReactiveMongoRepository<T, ID> extends ReactiveSortingRepository<T, ID> {
/**
* Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use
* the returned instance for further operations as the save operation might have changed the entity instance
* completely. Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
* Inserts the given entity. Assumes the instance to be new to be able to apply insertion optimizations. Use the
* returned instance for further operations as the save operation might have changed the entity instance completely.
* Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
*
* @param entity must not be {@literal null}.
* @return the saved entity
@@ -46,9 +44,9 @@ public interface ReactiveMongoRepository<T, ID extends Serializable> extends Rea
<S extends T> Mono<S> insert(S entity);
/**
* Inserts the given entities. Assumes the instance to be new to be able to apply insertion optimizations. Use
* the returned instance for further operations as the save operation might have changed the entity instance
* completely. Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
* Inserts the given entities. Assumes the instance to be new to be able to apply insertion optimizations. Use the
* returned instance for further operations as the save operation might have changed the entity instance completely.
* Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
*
* @param entities must not be {@literal null}.
* @return the saved entity
@@ -56,21 +54,23 @@ public interface ReactiveMongoRepository<T, ID extends Serializable> extends Rea
<S extends T> Flux<S> insert(Iterable<S> entities);
/**
* Inserts the given entities. Assumes the instance to be new to be able to apply insertion optimizations. Use
* the returned instance for further operations as the save operation might have changed the entity instance
* completely. Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
* Inserts the given entities. Assumes the instance to be new to be able to apply insertion optimizations. Use the
* returned instance for further operations as the save operation might have changed the entity instance completely.
* Prefer using {@link #save(Object)} instead to avoid the usage of store-specific API.
*
* @param entities must not be {@literal null}.
* @return the saved entity
*/
<S extends T> Flux<S> insert(Publisher<S> entities);
/* (non-Javadoc)
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)
*/
<S extends T> Flux<S> findAll(Example<S> example);
/* (non-Javadoc)
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
<S extends T> Flux<S> findAll(Example<S> example, Sort sort);

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.repository.query;
import java.io.Serializable;
import org.springframework.data.repository.core.EntityInformation;
/**
@@ -24,7 +22,7 @@ import org.springframework.data.repository.core.EntityInformation;
*
* @author Oliver Gierke
*/
public interface MongoEntityInformation<T, ID extends Serializable> extends EntityInformation<T, ID> {
public interface MongoEntityInformation<T, ID> extends EntityInformation<T, ID> {
/**
* Returns the name of the collection the entity shall be persisted to.
@@ -39,4 +37,4 @@ public interface MongoEntityInformation<T, ID extends Serializable> extends Enti
* @return
*/
String getIdAttribute();
}
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.repository.support;
import java.io.Serializable;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
@@ -30,7 +28,7 @@ import org.springframework.data.repository.core.support.PersistentEntityInformat
* @author Oliver Gierke
* @author Christoph Strobl
*/
public class MappingMongoEntityInformation<T, ID extends Serializable> extends PersistentEntityInformation<T, ID>
public class MappingMongoEntityInformation<T, ID> extends PersistentEntityInformation<T, ID>
implements MongoEntityInformation<T, ID> {
private final MongoPersistentEntity<T> entityMetadata;

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.data.mongodb.repository.support;
import java.io.Serializable;
import org.springframework.data.domain.Persistable;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
@@ -42,8 +40,7 @@ final class MongoEntityInformationSupport {
* @return never {@literal null}.
*/
@SuppressWarnings("unchecked")
static <T, ID extends Serializable> MongoEntityInformation<T, ID> entityInformationFor(
MongoPersistentEntity<?> entity, Class<?> idType) {
static <T, ID> MongoEntityInformation<T, ID> entityInformationFor(MongoPersistentEntity<?> entity, Class<?> idType) {
Assert.notNull(entity, "Entity must not be null!");

View File

@@ -23,7 +23,6 @@ import java.util.Optional;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
@@ -45,7 +44,6 @@ import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.data.repository.reactive.RxJava1CrudRepository;
import org.springframework.data.repository.util.QueryExecutionConverters;
import org.springframework.data.repository.util.ReactiveWrappers;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -91,18 +89,19 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport {
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
boolean isReactiveRepository = (PROJECT_REACTOR_PRESENT && ReactiveCrudRepository.class.isAssignableFrom(metadata.getRepositoryInterface())) || (
RXJAVA_OBSERVABLE_PRESENT && RxJava1CrudRepository.class.isAssignableFrom(metadata.getRepositoryInterface()));
boolean isReactiveRepository = (PROJECT_REACTOR_PRESENT
&& ReactiveCrudRepository.class.isAssignableFrom(metadata.getRepositoryInterface()))
|| (RXJAVA_OBSERVABLE_PRESENT
&& RxJava1CrudRepository.class.isAssignableFrom(metadata.getRepositoryInterface()));
boolean isQueryDslRepository = QUERY_DSL_PRESENT
&& QuerydslPredicateExecutor.class.isAssignableFrom(metadata.getRepositoryInterface());
if (isReactiveRepository) {
if(isQueryDslRepository) {
throw new InvalidDataAccessApiUsageException("Cannot combine Querydsl and reactive repository in one interface");
if (isQueryDslRepository) {
throw new InvalidDataAccessApiUsageException(
"Cannot combine Querydsl and reactive repository in one interface");
}
return SimpleReactiveMongoRepository.class;
}
@@ -127,7 +126,8 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport {
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getQueryLookupStrategy(org.springframework.data.repository.query.QueryLookupStrategy.Key, org.springframework.data.repository.query.EvaluationContextProvider)
*/
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) {
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key,
EvaluationContextProvider evaluationContextProvider) {
return Optional.of(new MongoQueryLookupStrategy(operations, evaluationContextProvider, mappingContext));
}
@@ -135,12 +135,11 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport {
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getEntityInformation(java.lang.Class)
*/
public <T, ID extends Serializable> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
public <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return getEntityInformation(domainClass, null);
}
@SuppressWarnings("unchecked")
private <T, ID extends Serializable> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass,
private <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass,
RepositoryInformation information) {
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(domainClass);

View File

@@ -18,7 +18,6 @@ package org.springframework.data.mongodb.repository.support;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.io.Serializable;
import java.util.Optional;
import org.springframework.data.domain.Persistable;
@@ -34,7 +33,7 @@ import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
* @since 1.10
*/
@RequiredArgsConstructor
class PersistableMongoEntityInformation<T, ID extends Serializable> implements MongoEntityInformation<T, ID> {
class PersistableMongoEntityInformation<T, ID> implements MongoEntityInformation<T, ID> {
private final @NonNull MongoEntityInformation<T, ID> delegate;

View File

@@ -90,10 +90,13 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
/*
* (non-Javadoc)
* @see org.springframework.data.querydsl.QueryDslPredicateExecutor#findOne(com.mysema.query.types.Predicate)
* @see org.springframework.data.querydsl.QuerydslPredicateExecutor#findById(com.querydsl.core.types.Predicate)
*/
@Override
public T findOne(Predicate predicate) {
Assert.notNull(predicate, "Predicate must not be null!");
return createQueryFor(predicate).fetchOne();
}
@@ -103,8 +106,10 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public List<T> findAll(Predicate predicate) {
List<T> list = createQueryFor(predicate).fetchResults().getResults();
return list;
Assert.notNull(predicate, "Predicate must not be null!");
return createQueryFor(predicate).fetchResults().getResults();
}
/*
@@ -113,6 +118,10 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public List<T> findAll(Predicate predicate, OrderSpecifier<?>... orders) {
Assert.notNull(predicate, "Predicate must not be null!");
Assert.notNull(orders, "Order specifiers must not be null!");
return createQueryFor(predicate).orderBy(orders).fetchResults().getResults();
}
@@ -122,6 +131,10 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public List<T> findAll(Predicate predicate, Sort sort) {
Assert.notNull(predicate, "Predicate must not be null!");
Assert.notNull(sort, "Sort must not be null!");
return applySorting(createQueryFor(predicate), sort).fetchResults().getResults();
}
@@ -131,6 +144,9 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public Iterable<T> findAll(OrderSpecifier<?>... orders) {
Assert.notNull(orders, "Order specifiers must not be null!");
return createQuery().orderBy(orders).fetchResults().getResults();
}
@@ -139,11 +155,15 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
* @see org.springframework.data.querydsl.QueryDslPredicateExecutor#findAll(com.mysema.query.types.Predicate, org.springframework.data.domain.Pageable)
*/
@Override
public Page<T> findAll(final Predicate predicate, Pageable pageable) {
public Page<T> findAll(Predicate predicate, Pageable pageable) {
Assert.notNull(predicate, "Predicate must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> query = createQueryFor(predicate);
return PageableExecutionUtils.getPage(applyPagination(query, pageable).fetchResults().getResults(), pageable, () -> createQueryFor(predicate).fetchCount());
return PageableExecutionUtils.getPage(applyPagination(query, pageable).fetchResults().getResults(), pageable,
() -> createQueryFor(predicate).fetchCount());
}
/*
@@ -153,9 +173,12 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
@Override
public Page<T> findAll(Pageable pageable) {
Assert.notNull(pageable, "Pageable must not be null!");
AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> query = createQuery();
return PageableExecutionUtils.getPage(applyPagination(query, pageable).fetchResults().getResults(), pageable, () -> createQuery().fetchCount());
return PageableExecutionUtils.getPage(applyPagination(query, pageable).fetchResults().getResults(), pageable,
() -> createQuery().fetchCount());
}
/*
@@ -164,6 +187,9 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public List<T> findAll(Sort sort) {
Assert.notNull(sort, "Sort must not be null!");
return applySorting(createQuery(), sort).fetchResults().getResults();
}
@@ -173,6 +199,9 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public long count(Predicate predicate) {
Assert.notNull(predicate, "Predicate must not be null!");
return createQueryFor(predicate).fetchCount();
}
@@ -182,6 +211,9 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
*/
@Override
public boolean exists(Predicate predicate) {
Assert.notNull(predicate, "Predicate must not be null!");
return createQueryFor(predicate).fetchCount() > 0;
}
@@ -214,10 +246,6 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
private AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> applyPagination(
AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> query, Pageable pageable) {
if (pageable == null) {
return query;
}
query = query.offset(pageable.getOffset()).limit(pageable.getPageSize());
return applySorting(query, pageable.getSort());
}
@@ -232,10 +260,6 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
private AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> applySorting(
AbstractMongodbQuery<T, SpringDataMongodbQuery<T>> query, Sort sort) {
if (sort == null) {
return query;
}
// TODO: find better solution than instanceof check
if (sort instanceof QSort) {
@@ -245,9 +269,7 @@ public class QueryDslMongoRepository<T, ID extends Serializable> extends SimpleM
return query;
}
for (Order order : sort) {
query.orderBy(toOrder(order));
}
sort.stream().map(this::toOrder).forEach(it -> query.orderBy(it));
return query;
}

View File

@@ -23,7 +23,6 @@ import java.lang.reflect.Method;
import java.util.Optional;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
@@ -98,7 +97,8 @@ public class ReactiveMongoRepositoryFactory extends ReactiveRepositoryFactorySup
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getQueryLookupStrategy(org.springframework.data.repository.query.QueryLookupStrategy.Key, org.springframework.data.repository.query.EvaluationContextProvider)
*/
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key, EvaluationContextProvider evaluationContextProvider) {
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key,
EvaluationContextProvider evaluationContextProvider) {
return Optional.of(new MongoQueryLookupStrategy(operations, evaluationContextProvider, mappingContext));
}
@@ -106,22 +106,17 @@ public class ReactiveMongoRepositoryFactory extends ReactiveRepositoryFactorySup
* (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getEntityInformation(java.lang.Class)
*/
public <T, ID extends Serializable> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
public <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return getEntityInformation(domainClass, null);
}
@SuppressWarnings("unchecked")
private <T, ID extends Serializable> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass,
private <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass,
RepositoryInformation information) {
Optional<? extends MongoPersistentEntity<?>> entity = mappingContext.getPersistentEntity(domainClass);
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(domainClass);
if (!entity.isPresent()) {
throw new MappingException(
String.format("Could not lookup mapping metadata for domain class %s!", domainClass.getName()));
}
return new MappingMongoEntityInformation<T, ID>((MongoPersistentEntity<T>) entity.get(),
return new MappingMongoEntityInformation<T, ID>((MongoPersistentEntity<T>) entity,
information != null ? (Class<ID>) information.getIdType() : null);
}

View File

@@ -18,13 +18,10 @@ package org.springframework.data.mongodb.repository.support;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
@@ -38,6 +35,8 @@ import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.data.util.StreamUtils;
import org.springframework.data.util.Streamable;
import org.springframework.util.Assert;
/**
@@ -72,6 +71,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
*/
@Override
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Entity must not be null!");
@@ -87,57 +87,49 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#save(java.lang.Iterable)
* @see org.springframework.data.mongodb.repository.MongoRepository#saveAll(java.lang.Iterable)
*/
public <S extends T> List<S> save(Iterable<S> entities) {
@Override
public <S extends T> List<S> saveAll(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities not be null!");
List<S> result = convertIterableToList(entities);
boolean allNew = true;
for (S entity : entities) {
if (allNew && !entityInformation.isNew(entity)) {
allNew = false;
}
}
Streamable<S> source = Streamable.of(entities);
boolean allNew = source.stream().allMatch(it -> entityInformation.isNew(it));
if (allNew) {
List<S> result = source.stream().collect(Collectors.toList());
mongoOperations.insertAll(result);
return result;
} else {
for (S entity : result) {
save(entity);
}
return source.stream().map(this::save).collect(Collectors.toList());
}
return result;
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
public Optional<T> findOne(ID id) {
@Override
public Optional<T> findById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return Optional.ofNullable(mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()));
}
private Query getIdQuery(Object id) {
return new Query(getIdCriteria(id));
}
private Criteria getIdCriteria(Object id) {
return where(entityInformation.getIdAttribute()).is(id);
return Optional.ofNullable(
mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#exists(java.io.Serializable)
* @see org.springframework.data.repository.CrudRepository#existsById(java.lang.Object)
*/
public boolean exists(ID id) {
@Override
public boolean existsById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.exists(getIdQuery(id), entityInformation.getJavaType(),
entityInformation.getCollectionName());
}
@@ -146,16 +138,20 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#count()
*/
@Override
public long count() {
return mongoOperations.getCollection(entityInformation.getCollectionName()).count();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#delete(java.io.Serializable)
* @see org.springframework.data.repository.CrudRepository#deleteById(java.lang.Object)
*/
public void delete(ID id) {
@Override
public void deleteById(ID id) {
Assert.notNull(id, "The given id must not be null!");
mongoOperations.remove(getIdQuery(id), entityInformation.getJavaType(), entityInformation.getCollectionName());
}
@@ -163,28 +159,31 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#delete(java.lang.Object)
*/
@Override
public void delete(T entity) {
Assert.notNull(entity, "The given entity must not be null!");
delete(entityInformation.getId(entity).orElse(null));
deleteById(entityInformation.getRequiredId(entity));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#delete(java.lang.Iterable)
*/
public void delete(Iterable<? extends T> entities) {
@Override
public void deleteAll(Iterable<? extends T> entities) {
Assert.notNull(entities, "The given Iterable of entities not be null!");
for (T entity : entities) {
delete(entity);
}
entities.forEach(this::delete);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#deleteAll()
*/
@Override
public void deleteAll() {
mongoOperations.remove(new Query(), entityInformation.getCollectionName());
}
@@ -193,29 +192,30 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll()
*/
@Override
public List<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll(java.lang.Iterable)
* @see org.springframework.data.repository.CrudRepository#findAllById(java.lang.Iterable)
*/
public Iterable<T> findAll(Iterable<ID> ids) {
@Override
public Iterable<T> findAllById(Iterable<ID> ids) {
Set<ID> parameters = new HashSet<ID>(tryDetermineRealSizeOrReturn(ids, 10));
for (ID id : ids) {
parameters.add(id);
}
return findAll(new Query(new Criteria(entityInformation.getIdAttribute()).in(parameters)));
return findAll(new Query(new Criteria(entityInformation.getIdAttribute())
.in(Streamable.of(ids).stream().collect(StreamUtils.toUnmodifiableList()))));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Pageable)
*/
public Page<T> findAll(final Pageable pageable) {
@Override
public Page<T> findAll(Pageable pageable) {
Assert.notNull(pageable, "Pageable must not be null!");
Long count = count();
List<T> list = findAll(new Query().with(pageable));
@@ -227,7 +227,11 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
* (non-Javadoc)
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
@Override
public List<T> findAll(Sort sort) {
Assert.notNull(sort, "Sort must not be null!");
return findAll(new Query().with(sort));
}
@@ -253,7 +257,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
Assert.notNull(entities, "The given Iterable of entities not be null!");
List<S> list = convertIterableToList(entities);
List<S> list = Streamable.of(entities).stream().collect(StreamUtils.toUnmodifiableList());
if (list.isEmpty()) {
return list;
@@ -271,13 +275,13 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
public <S extends T> Page<S> findAll(final Example<S> example, Pageable pageable) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
final Query q = new Query(new Criteria().alike(example)).with(pageable);
Query q = new Query(new Criteria().alike(example)).with(pageable);
List<S> list = mongoOperations.find(q, example.getProbeType(), entityInformation.getCollectionName());
return PageableExecutionUtils.getPage(list, pageable, () ->
mongoOperations.count(q, example.getProbeType(), entityInformation.getCollectionName())
);
return PageableExecutionUtils.getPage(list, pageable,
() -> mongoOperations.count(q, example.getProbeType(), entityInformation.getCollectionName()));
}
/*
@@ -288,12 +292,9 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
public <S extends T> List<S> findAll(Example<S> example, Sort sort) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(sort, "Sort must not be null!");
Query q = new Query(new Criteria().alike(example));
if (sort != null) {
q.with(sort);
}
Query q = new Query(new Criteria().alike(example)).with(sort);
return mongoOperations.find(q, example.getProbeType(), entityInformation.getCollectionName());
}
@@ -304,7 +305,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
*/
@Override
public <S extends T> List<S> findAll(Example<S> example) {
return findAll(example, (Sort) null);
return findAll(example, Sort.unsorted());
}
/*
@@ -346,6 +347,14 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
return mongoOperations.exists(q, example.getProbeType(), entityInformation.getCollectionName());
}
private Query getIdQuery(Object id) {
return new Query(getIdCriteria(id));
}
private Criteria getIdCriteria(Object id) {
return where(entityInformation.getIdAttribute()).is(id);
}
private List<T> findAll(Query query) {
if (query == null) {
@@ -354,29 +363,4 @@ public class SimpleMongoRepository<T, ID extends Serializable> implements MongoR
return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
private static <T> List<T> convertIterableToList(Iterable<T> entities) {
if (entities instanceof List) {
return (List<T>) entities;
}
int capacity = tryDetermineRealSizeOrReturn(entities, 10);
if (capacity == 0 || entities == null) {
return Collections.<T> emptyList();
}
List<T> list = new ArrayList<T>(capacity);
for (T entity : entities) {
list.add(entity);
}
return list;
}
private static int tryDetermineRealSizeOrReturn(Iterable<?> iterable, int defaultSize) {
return iterable == null ? 0 : (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : defaultSize;
}
}

View File

@@ -17,13 +17,14 @@ package org.springframework.data.mongodb.repository.support;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.reactivestreams.Publisher;
import org.springframework.data.domain.Example;
@@ -33,47 +34,41 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.util.StreamUtils;
import org.springframework.data.util.Streamable;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Reactive repository base implementation for Mongo.
*
* @author Mark Paluch
* @author Oliver Gierke
* @since 2.0
*/
@RequiredArgsConstructor
public class SimpleReactiveMongoRepository<T, ID extends Serializable> implements ReactiveMongoRepository<T, ID> {
private final ReactiveMongoOperations mongoOperations;
private final MongoEntityInformation<T, ID> entityInformation;
private final @NonNull MongoEntityInformation<T, ID> entityInformation;
private final @NonNull ReactiveMongoOperations mongoOperations;
/**
* Creates a new {@link SimpleReactiveMongoRepository} for the given {@link MongoEntityInformation} and
* {@link ReactiveMongoOperations}.
*
* @param metadata must not be {@literal null}.
* @param mongoOperations must not be {@literal null}.
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(java.lang.Object)
*/
public SimpleReactiveMongoRepository(MongoEntityInformation<T, ID> metadata,
ReactiveMongoOperations mongoOperations) {
Assert.notNull(metadata, "MongoEntityInformation must not be null!");
Assert.notNull(mongoOperations, "ReactiveMongoOperations must not be null!");
this.entityInformation = metadata;
this.mongoOperations = mongoOperations;
}
public Mono<T> findOne(ID id) {
@Override
public Mono<T> findById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
public Mono<T> findOne(Mono<ID> mono) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findById(reactor.core.publisher.Mono)
*/
@Override
public Mono<T> findById(Mono<ID> mono) {
Assert.notNull(mono, "The given id must not be null!");
@@ -81,15 +76,12 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
id -> mongoOperations.findById(id, entityInformation.getJavaType(), entityInformation.getCollectionName()));
}
public <S extends T> Mono<S> findOne(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.findOne(q, example.getProbeType(), entityInformation.getCollectionName());
}
public Mono<Boolean> exists(ID id) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(java.lang.Object)
*/
@Override
public Mono<Boolean> existsById(ID id) {
Assert.notNull(id, "The given id must not be null!");
@@ -97,7 +89,12 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
entityInformation.getCollectionName());
}
public Mono<Boolean> exists(Mono<ID> mono) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#existsById(reactor.core.publisher.Mono)
*/
@Override
public Mono<Boolean> existsById(Mono<ID> mono) {
Assert.notNull(mono, "The given id must not be null!");
@@ -106,76 +103,81 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
}
public <S extends T> Mono<Boolean> exists(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.exists(q, example.getProbeType(), entityInformation.getCollectionName());
}
@Override
public Flux<T> findAll() {
return findAll(new Query());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(java.lang.Iterable)
*/
@Override
public Flux<T> findAll(Iterable<ID> ids) {
public Flux<T> findAllById(Iterable<ID> ids) {
Assert.notNull(ids, "The given Iterable of Id's must not be null!");
Set<ID> parameters = new HashSet<ID>(tryDetermineRealSizeOrReturn(ids, 10));
for (ID id : ids) {
parameters.add(id);
}
return findAll(new Query(new Criteria(entityInformation.getIdAttribute()).in(parameters)));
return findAll(new Query(new Criteria(entityInformation.getIdAttribute())
.in(Streamable.of(ids).stream().collect(StreamUtils.toUnmodifiableList()))));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#findAllById(org.reactivestreams.Publisher)
*/
@Override
public Flux<T> findAll(Publisher<ID> idStream) {
public Flux<T> findAllById(Publisher<ID> ids) {
Assert.notNull(idStream, "The given Publisher of Id's must not be null!");
Assert.notNull(ids, "The given Publisher of Id's must not be null!");
return Flux.from(idStream).buffer().flatMap(this::findAll);
return Flux.from(ids).buffer().flatMap(this::findAllById);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
@Override
public Flux<T> findAll(Sort sort) {
return findAll(new Query().with(sort));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example, Sort sort) {
Assert.notNull(example, "Sample must not be null!");
Assert.notNull(sort, "Sort must not be null!");
Query q = new Query(new Criteria().alike(example));
Query query = new Query(new Criteria().alike(example)).with(sort);
if (sort != null) {
q.with(sort);
}
return mongoOperations.find(q, example.getProbeType(), entityInformation.getCollectionName());
return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#findAll(org.springframework.data.domain.Example)
*/
@Override
public <S extends T> Flux<S> findAll(Example<S> example) {
return findAll(example, null);
return findAll(example, Sort.unsorted());
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#count()
*/
public Mono<Long> count() {
return mongoOperations.count(new Query(), entityInformation.getCollectionName());
}
public <S extends T> Mono<Long> count(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.count(q, example.getProbeType(), entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Object)
*/
@Override
public <S extends T> Mono<S> insert(S entity) {
@@ -184,20 +186,24 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return mongoOperations.insert(entity, entityInformation.getCollectionName());
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(java.lang.Iterable)
*/
@Override
public <S extends T> Flux<S> insert(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
List<S> list = convertIterableToList(entities);
List<S> source = Streamable.of(entities).stream().collect(StreamUtils.toUnmodifiableList());
if (list.isEmpty()) {
return Flux.empty();
}
return Flux.from(mongoOperations.insertAll(list));
return source.isEmpty() ? Flux.empty() : Flux.from(mongoOperations.insertAll(source));
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.repository.ReactiveMongoRepository#insert(org.reactivestreams.Publisher)
*/
@Override
public <S extends T> Flux<S> insert(Publisher<S> entities) {
@@ -206,6 +212,11 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return Flux.from(entities).flatMap(entity -> mongoOperations.insert(entity, entityInformation.getCollectionName()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#save(java.lang.Object)
*/
@Override
public <S extends T> Mono<S> save(S entity) {
Assert.notNull(entity, "Entity must not be null!");
@@ -217,85 +228,119 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return mongoOperations.save(entity, entityInformation.getCollectionName());
}
public <S extends T> Flux<S> save(Iterable<S> entities) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#saveAll(java.lang.Iterable)
*/
@Override
public <S extends T> Flux<S> saveAll(Iterable<S> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
List<S> result = convertIterableToList(entities);
boolean allNew = true;
Streamable<S> source = Streamable.of(entities);
for (S entity : entities) {
if (allNew && !entityInformation.isNew(entity)) {
allNew = false;
}
}
if (allNew) {
return Flux.from(mongoOperations.insertAll(result));
}
List<Mono<S>> monos = new ArrayList<>();
for (S entity : result) {
monos.add(save(entity));
}
return Flux.merge(monos);
return source.stream().allMatch(it -> entityInformation.isNew(it)) ? //
mongoOperations.insertAll(source.stream().collect(Collectors.toList())) : //
Flux.fromIterable(entities).flatMap(this::save);
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#saveAll(org.reactivestreams.Publisher)
*/
@Override
public <S extends T> Flux<S> save(Publisher<S> entityStream) {
public <S extends T> Flux<S> saveAll(Publisher<S> entityStream) {
Assert.notNull(entityStream, "The given Publisher of entities must not be null!");
return Flux.from(entityStream).flatMap(entity -> {
if (entityInformation.isNew(entity)) {
return mongoOperations.insert(entity, entityInformation.getCollectionName()).then(Mono.just(entity));
}
return mongoOperations.save(entity, entityInformation.getCollectionName()).then(Mono.just(entity));
});
return Flux.from(entityStream)
.flatMap(entity -> entityInformation.isNew(entity) ? //
mongoOperations.insert(entity, entityInformation.getCollectionName()).then(Mono.just(entity)) : //
mongoOperations.save(entity, entityInformation.getCollectionName()).then(Mono.just(entity)));
}
// TODO: should this one really be void?
public Mono<Void> delete(ID id) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteById(java.lang.Object)
*/
@Override
public Mono<Void> deleteById(ID id) {
Assert.notNull(id, "The given id must not be null!");
return mongoOperations
.remove(getIdQuery(id), entityInformation.getJavaType(), entityInformation.getCollectionName()).then();
}
// TODO: should this one really be void?
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#delete(java.lang.Object)
*/
@Override
public Mono<Void> delete(T entity) {
Assert.notNull(entity, "The given entity must not be null!");
return delete(entityInformation.getId(entity).get());
return deleteById(entityInformation.getRequiredId(entity));
}
// TODO: should this one really be void?
public Mono<Void> delete(Iterable<? extends T> entities) {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteAll(java.lang.Iterable)
*/
@Override
public Mono<Void> deleteAll(Iterable<? extends T> entities) {
Assert.notNull(entities, "The given Iterable of entities must not be null!");
return Flux.fromIterable(entities).flatMap(entity -> delete(entityInformation.getId(entity).get())).then();
return Flux.fromIterable(entities).flatMap(entity -> deleteById(entityInformation.getRequiredId(entity))).then();
}
// TODO: should this one really be void?
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteAll(org.reactivestreams.Publisher)
*/
@Override
public Mono<Void> delete(Publisher<? extends T> entityStream) {
public Mono<Void> deleteAll(Publisher<? extends T> entityStream) {
Assert.notNull(entityStream, "The given Publisher of entities must not be null!");
return Flux.from(entityStream).flatMap(entity -> delete(entityInformation.getId(entity).get())).then();
return Flux.from(entityStream)//
.map(it -> entityInformation.getRequiredId(it))//
.flatMap(this::deleteById)//
.then();
}
// TODO: should this one really be void?
/*
* (non-Javadoc)
* @see org.springframework.data.repository.reactive.ReactiveCrudRepository#deleteAll()
*/
public Mono<Void> deleteAll() {
return mongoOperations.remove(new Query(), entityInformation.getCollectionName())
.then(Mono.empty());
return mongoOperations.remove(new Query(), entityInformation.getCollectionName()).then(Mono.empty());
}
public <S extends T> Mono<Boolean> exists(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.exists(q, example.getProbeType(), entityInformation.getCollectionName());
}
public <S extends T> Mono<S> findOne(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.findOne(q, example.getProbeType(), entityInformation.getCollectionName());
}
public <S extends T> Mono<Long> count(Example<S> example) {
Assert.notNull(example, "Sample must not be null!");
Query q = new Query(new Criteria().alike(example));
return mongoOperations.count(q, example.getProbeType(), entityInformation.getCollectionName());
}
private Query getIdQuery(Object id) {
@@ -314,29 +359,4 @@ public class SimpleReactiveMongoRepository<T, ID extends Serializable> implement
return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName());
}
private static <T> List<T> convertIterableToList(Iterable<T> entities) {
if (entities instanceof List) {
return (List<T>) entities;
}
int capacity = tryDetermineRealSizeOrReturn(entities, 10);
if (capacity == 0 || entities == null) {
return Collections.emptyList();
}
List<T> list = new ArrayList<T>(capacity);
for (T entity : entities) {
list.add(entity);
}
return list;
}
private static int tryDetermineRealSizeOrReturn(Iterable<?> iterable, int defaultSize) {
return iterable == null ? 0 : (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : defaultSize;
}
}

View File

@@ -34,7 +34,6 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
/**
@@ -107,7 +106,7 @@ public class NoExplicitIdTests {
Map<String, Object> map = mongoOps.findOne(query(where("someString").is(noid.someString)), Map.class,
"typeWithoutIdProperty");
Optional<TypeWithoutIdProperty> retrieved = repo.findOne(map.get("_id").toString());
Optional<TypeWithoutIdProperty> retrieved = repo.findById(map.get("_id").toString());
assertThat(retrieved.get().someString, is(noid.someString));
}

View File

@@ -31,6 +31,7 @@ import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.bson.Document;
import org.bson.types.ObjectId;
@@ -44,7 +45,6 @@ import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean;
import org.springframework.util.Assert;
@@ -57,7 +57,6 @@ import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
@@ -226,22 +225,13 @@ public class PerformanceTests {
}
private long queryUsingTemplate() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
Query query = query(where("addresses.zipCode").regex(".*1.*"));
return operations.find(query, Person.class, "template");
}
});
executeWatched(() -> operations.find(query(where("addresses.zipCode").regex(".*1.*")), Person.class, "template"));
return watch.getLastTaskTimeMillis();
}
private long queryUsingRepository() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
return repository.findByAddressesZipCodeContaining("1");
}
});
executeWatched(() -> repository.findByAddressesZipCodeContaining("1"));
return watch.getLastTaskTimeMillis();
}
@@ -288,93 +278,62 @@ public class PerformanceTests {
private long writingObjectsUsingPlainDriver(int numberOfPersons) {
final DBCollection collection = mongo.getDB(DATABASE_NAME).getCollection("driver");
final List<Person> persons = getPersonObjects(numberOfPersons);
DBCollection collection = mongo.getDB(DATABASE_NAME).getCollection("driver");
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
for (Person person : persons) {
collection.save(new BasicDBObject(person.toDocument()));
}
return null;
}
});
executeWatched(() -> persons.stream().map(it -> collection.save(new BasicDBObject(it.toDocument()))));
return watch.getLastTaskTimeMillis();
}
private long writingObjectsUsingRepositories(int numberOfPersons) {
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
repository.save(persons);
return null;
}
});
executeWatched(() -> repository.saveAll(persons));
return watch.getLastTaskTimeMillis();
}
private long writingObjectsUsingMongoTemplate(int numberOfPersons) {
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
for (Person person : persons) {
operations.save(person, "template");
}
return null;
}
});
executeWatched(() -> persons.stream()//
.peek(it -> operations.save(it, "template"))//
.collect(Collectors.toList()));
return watch.getLastTaskTimeMillis();
}
private long readingUsingPlainDriver() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
return toPersons(mongo.getDB(DATABASE_NAME).getCollection("driver").find());
}
});
executeWatched(() -> toPersons(mongo.getDB(DATABASE_NAME).getCollection("driver").find()));
return watch.getLastTaskTimeMillis();
}
private long readingUsingTemplate() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
return operations.findAll(Person.class, "template");
}
});
executeWatched(() -> operations.findAll(Person.class, "template"));
return watch.getLastTaskTimeMillis();
}
private long readingUsingRepository() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
return repository.findAll();
}
});
executeWatched(repository::findAll);
return watch.getLastTaskTimeMillis();
}
private long queryUsingPlainDriver() {
executeWatched(new WatchCallback<List<Person>>() {
public List<Person> doInWatch() {
executeWatched(() -> {
DBCollection collection = mongo.getDB(DATABASE_NAME).getCollection("driver");
DBCollection collection = mongo.getDB(DATABASE_NAME).getCollection("driver");
BasicDBObject regex = new BasicDBObject("$regex", Pattern.compile(".*1.*"));
BasicDBObject query = new BasicDBObject("addresses.zipCode", regex);
return toPersons(collection.find(query));
}
BasicDBObject regex = new BasicDBObject("$regex", Pattern.compile(".*1.*"));
BasicDBObject query = new BasicDBObject("addresses.zipCode", regex);
return toPersons(collection.find(query));
});
return watch.getLastTaskTimeMillis();

View File

@@ -18,7 +18,6 @@ package org.springframework.data.mongodb.performance;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -58,6 +57,7 @@ import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.data.mongodb.repository.support.ReactiveMongoRepositoryFactory;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;
@@ -107,8 +107,8 @@ public class ReactivePerformanceTests {
converter = new MappingMongoConverter(new DbRefResolver() {
@Override
public Optional<Object> resolveDbRef(MongoPersistentProperty property, DBRef dbref, DbRefResolverCallback callback,
DbRefProxyHandler proxyHandler) {
public Optional<Object> resolveDbRef(MongoPersistentProperty property, DBRef dbref,
DbRefResolverCallback callback, DbRefProxyHandler proxyHandler) {
return Optional.empty();
}
@@ -307,18 +307,12 @@ public class ReactivePerformanceTests {
private long writingObjectsUsingPlainDriver(int numberOfPersons, WriteConcern concern) {
final MongoCollection<Document> collection = mongo.getDatabase(DATABASE_NAME).getCollection("driver")
MongoCollection<Document> collection = mongo.getDatabase(DATABASE_NAME).getCollection("driver")
.withWriteConcern(concern);
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
for (Person person : persons) {
Mono.from(collection.insertOne(new Document(person.toDocument()))).block();
}
return null;
}
});
executeWatched(
() -> persons.stream().map(it -> Mono.from(collection.insertOne(new Document(it.toDocument()))).block()));
return watch.getLastTaskTimeMillis();
}
@@ -327,14 +321,7 @@ public class ReactivePerformanceTests {
final List<Person> persons = getPersonObjects(numberOfPersons);
operations.setWriteConcern(concern);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
for (Person person : persons) {
repository.save(person).block();
}
return null;
}
});
executeWatched(() -> persons.stream().map(it -> repository.save(it).block()));
return watch.getLastTaskTimeMillis();
}
@@ -343,14 +330,9 @@ public class ReactivePerformanceTests {
final List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
operations.setWriteConcern(concern);
for (Person person : persons) {
Mono.from(operations.save(person, "template")).block();
}
return null;
}
executeWatched(() -> {
operations.setWriteConcern(concern);
return persons.stream().map(it -> operations.save(it, "template").block());
});
return watch.getLastTaskTimeMillis();
@@ -358,47 +340,34 @@ public class ReactivePerformanceTests {
private long writingAsyncObjectsUsingPlainDriver(int numberOfPersons, WriteConcern concern) {
final MongoCollection<Document> collection = mongo.getDatabase(DATABASE_NAME).getCollection("driver")
MongoCollection<Document> collection = mongo.getDatabase(DATABASE_NAME).getCollection("driver")
.withWriteConcern(concern);
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
Flux.from(collection
executeWatched(() -> Flux
.from(collection
.insertMany(persons.stream().map(person -> new Document(person.toDocument())).collect(Collectors.toList())))
.then().block();
return null;
}
});
.then().block());
return watch.getLastTaskTimeMillis();
}
private long writingAsyncObjectsUsingRepositories(int numberOfPersons, WriteConcern concern) {
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
operations.setWriteConcern(concern);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
repository.save(persons).then().block();
return null;
}
});
executeWatched(() -> repository.saveAll(persons).then().block());
return watch.getLastTaskTimeMillis();
}
private long writingAsyncObjectsUsingMongoTemplate(int numberOfPersons, WriteConcern concern) {
final List<Person> persons = getPersonObjects(numberOfPersons);
List<Person> persons = getPersonObjects(numberOfPersons);
executeWatched(new WatchCallback<Void>() {
public Void doInWatch() {
operations.setWriteConcern(concern);
Flux.from(operations.insertAll(persons)).then().block();
return null;
}
executeWatched(() -> {
operations.setWriteConcern(concern);
return Flux.from(operations.insertAll(persons)).then().block();
});
return watch.getLastTaskTimeMillis();

View File

@@ -104,13 +104,13 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
person = new QPerson("person");
all = repository.save(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia));
all = repository.saveAll(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia));
}
@Test
public void findsPersonById() throws Exception {
assertThat(repository.findOne(dave.getId().toString()), is(Optional.of(dave)));
assertThat(repository.findById(dave.getId().toString()), is(Optional.of(dave)));
}
@Test
@@ -123,7 +123,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test
public void findsAllWithGivenIds() {
Iterable<Person> result = repository.findAll(Arrays.asList(dave.id, boyd.id));
Iterable<Person> result = repository.findAllById(Arrays.asList(dave.id, boyd.id));
assertThat(result, hasItems(dave, boyd));
assertThat(result, not(hasItems(oliver, carter, stefan, leroi, alicia)));
}
@@ -142,7 +142,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test
public void deletesPersonByIdCorrectly() {
repository.delete(dave.getId().toString());
repository.deleteById(dave.getId().toString());
List<Person> result = repository.findAll();
@@ -377,7 +377,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test // DATADOC-190
public void existsWorksCorrectly() {
assertThat(repository.exists(dave.getId()), is(true));
assertThat(repository.existsById(dave.getId()), is(true));
}
@Test(expected = DuplicateKeyException.class)
@@ -602,7 +602,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
boyd.setLocation(here);
leroi.setLocation(here);
repository.save(Arrays.asList(dave, oliver, carter, boyd, leroi));
repository.saveAll(Arrays.asList(dave, oliver, carter, boyd, leroi));
GeoPage<Person> results = repository.findByLocationNear(new Point(-73.99, 40.73),
new Distance(2000, Metrics.KILOMETERS), PageRequest.of(1, 2));
@@ -624,7 +624,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
oliver.setLocation(point);
carter.setLocation(point);
repository.save(Arrays.asList(dave, oliver, carter));
repository.saveAll(Arrays.asList(dave, oliver, carter));
GeoPage<Person> results = repository.findByLocationNear(new Point(-73.99, 40.73),
new Distance(2000, Metrics.KILOMETERS), PageRequest.of(1, 2));
@@ -858,7 +858,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test // DATAMONGO-950
public void shouldLimitCollectionQueryToMaxResultsWhenPresent() {
repository.save(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
repository.saveAll(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
new Person("Bob-3", "Dylan"), new Person("Bob-4", "Dylan"), new Person("Bob-5", "Dylan")));
List<Person> result = repository.findTop3ByLastnameStartingWith("Dylan");
assertThat(result.size(), is(3));
@@ -867,7 +867,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test // DATAMONGO-950, DATAMONGO-1464
public void shouldNotLimitPagedQueryWhenPageRequestWithinBounds() {
repository.save(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
repository.saveAll(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
new Person("Bob-3", "Dylan"), new Person("Bob-4", "Dylan"), new Person("Bob-5", "Dylan")));
Page<Person> result = repository.findTop3ByLastnameStartingWith("Dylan", PageRequest.of(0, 2));
assertThat(result.getContent().size(), is(2));
@@ -877,7 +877,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test // DATAMONGO-950
public void shouldLimitPagedQueryWhenPageRequestExceedsUpperBoundary() {
repository.save(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
repository.saveAll(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
new Person("Bob-3", "Dylan"), new Person("Bob-4", "Dylan"), new Person("Bob-5", "Dylan")));
Page<Person> result = repository.findTop3ByLastnameStartingWith("Dylan", PageRequest.of(1, 2));
assertThat(result.getContent().size(), is(1));
@@ -886,7 +886,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
@Test // DATAMONGO-950, DATAMONGO-1464
public void shouldReturnEmptyWhenPageRequestedPageIsTotallyOutOfScopeForLimit() {
repository.save(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
repository.saveAll(Arrays.asList(new Person("Bob-1", "Dylan"), new Person("Bob-2", "Dylan"),
new Person("Bob-3", "Dylan"), new Person("Bob-4", "Dylan"), new Person("Bob-5", "Dylan")));
Page<Person> result = repository.findTop3ByLastnameStartingWith("Dylan", PageRequest.of(100, 2));
assertThat(result.getContent().size(), is(0));
@@ -946,7 +946,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
persons.add(new Person(String.format("%03d", i), "ln" + 1, 100));
}
repository.save(persons);
repository.saveAll(persons);
Slice<Person> slice = repository.findByAgeGreaterThan(50, PageRequest.of(0, 20, Direction.ASC, "firstname"));
assertThat(slice, contains(persons.subList(0, 20).toArray()));
@@ -985,7 +985,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
persons.add(person);
}
repository.save(persons);
repository.saveAll(persons);
QPerson person = QPerson.person;
@@ -1008,7 +1008,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
persons.add(person);
}
repository.save(persons);
repository.saveAll(persons);
PageRequest pageRequest = PageRequest.of(0, 2, new QSort(person.address.street.desc()));
Iterable<Person> result = repository.findAll(pageRequest);
@@ -1030,7 +1030,7 @@ public abstract class AbstractPersonRepositoryIntegrationTests {
persons.add(person);
}
repository.save(persons);
repository.saveAll(persons);
Iterable<Person> result = repository.findAll(new QSort(person.address.street.desc()));

View File

@@ -35,7 +35,6 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
/**
@@ -107,7 +106,7 @@ public class ComplexIdRepositoryIntegrationTests {
repo.save(userWithId);
assertThat(repo.findOne(id), is(Optional.of(userWithId)));
assertThat(repo.findById(id), is(Optional.of(userWithId)));
}
@Test // DATAMONGO-1078
@@ -115,7 +114,7 @@ public class ComplexIdRepositoryIntegrationTests {
repo.save(userWithId);
Iterable<UserWithComplexId> loaded = repo.findAll(Collections.singleton(id));
Iterable<UserWithComplexId> loaded = repo.findAllById(Collections.singleton(id));
assertThat(loaded, is(Matchers.<UserWithComplexId> iterableWithSize(1)));
assertThat(loaded, contains(userWithId));

View File

@@ -49,7 +49,7 @@ public class ContactRepositoryIntegrationTests {
Person person = new Person("Oliver", "Gierke");
Contact result = repository.save(person);
assertTrue(repository.findOne(result.getId().toString()).get() instanceof Person);
assertTrue(repository.findById(result.getId().toString()).get() instanceof Person);
}
@Test // DATAMONGO-1245

View File

@@ -84,14 +84,14 @@ public class ConvertingReactiveMongoRepositoryTests {
leroi = new ReactivePerson("Leroi", "Moore", 41);
alicia = new ReactivePerson("Alicia", "Keys", 30);
StepVerifier.create(reactiveRepository.save(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
StepVerifier.create(reactiveRepository.saveAll(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
.expectNextCount(7) //
.verifyComplete();
}
@Test // DATAMONGO-1444
public void reactiveStreamsMethodsShouldWork() {
StepVerifier.create(reactivePersonRepostitory.exists(dave.getId())).expectNext(true).verifyComplete();
StepVerifier.create(reactivePersonRepostitory.existsById(dave.getId())).expectNext(true).verifyComplete();
}
@Test // DATAMONGO-1444
@@ -102,7 +102,7 @@ public class ConvertingReactiveMongoRepositoryTests {
@Test // DATAMONGO-1444
public void simpleRxJava1MethodsShouldWork() throws Exception {
rxJava1PersonRepostitory.exists(dave.getId()) //
rxJava1PersonRepostitory.existsById(dave.getId()) //
.test() //
.awaitTerminalEvent() //
.assertValue(true) //
@@ -113,7 +113,7 @@ public class ConvertingReactiveMongoRepositoryTests {
@Test // DATAMONGO-1444
public void existsWithSingleRxJava1IdMethodsShouldWork() throws Exception {
rxJava1PersonRepostitory.exists(Single.just(dave.getId())) //
rxJava1PersonRepostitory.existsById(Single.just(dave.getId())) //
.test() //
.awaitTerminalEvent() //
.assertValue(true) //
@@ -162,7 +162,7 @@ public class ConvertingReactiveMongoRepositoryTests {
@Test // DATAMONGO-1610
public void simpleRxJava2MethodsShouldWork() throws Exception {
TestObserver<Boolean> testObserver = rxJava2PersonRepostitory.exists(dave.getId()).test();
TestObserver<Boolean> testObserver = rxJava2PersonRepostitory.existsById(dave.getId()).test();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();
@@ -173,7 +173,8 @@ public class ConvertingReactiveMongoRepositoryTests {
@Test // DATAMONGO-1610
public void existsWithSingleRxJava2IdMethodsShouldWork() throws Exception {
TestObserver<Boolean> testObserver = rxJava2PersonRepostitory.exists(io.reactivex.Single.just(dave.getId())).test();
TestObserver<Boolean> testObserver = rxJava2PersonRepostitory.existsById(io.reactivex.Single.just(dave.getId()))
.test();
testObserver.awaitTerminalEvent();
testObserver.assertComplete();

View File

@@ -50,7 +50,6 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
/**
@@ -79,8 +78,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
@Before
public void setUp() {
template.indexOps(FullTextDocument.class).ensureIndex(
new TextIndexDefinitionBuilder().onField("title").onField("content").build());
template.indexOps(FullTextDocument.class)
.ensureIndex(new TextIndexDefinitionBuilder().onField("title").onField("content").build());
this.repo = new MongoRepositoryFactory(this.template).getRepository(FullTextRepository.class);
}
@@ -104,9 +103,7 @@ public class MongoRepositoryTextSearchIntegrationTests {
public void derivedFinderWithTextCriteriaReturnsCorrectResult() {
initRepoWithDefaultDocuments();
FullTextDocument blade = new FullTextDocument(
"4",
"Blade",
FullTextDocument blade = new FullTextDocument("4", "Blade",
"Blade is a 1998 American vampire-superhero-vigilante action film starring Wesley Snipes and Stephen Dorff, loosely based on the Marvel Comics character Blade");
blade.nonTextIndexProperty = "foo";
repo.save(blade);
@@ -123,8 +120,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
initRepoWithDefaultDocuments();
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("film"), PageRequest.of(1,
1, Direction.ASC, "id"));
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("film"),
PageRequest.of(1, 1, Direction.ASC, "id"));
assertThat(page.hasNext(), is(true));
assertThat(page.hasPrevious(), is(true));
@@ -139,8 +136,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
FullTextDocument snipes = new FullTextDocument("4", "Snipes", "Wesley Trent Snipes is an actor and film producer.");
repo.save(snipes);
List<FullTextDocument> result = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"), Sort.by(
"score"));
List<FullTextDocument> result = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"),
Sort.by("score"));
assertThat(result.size(), is(4));
assertThat(result.get(0), equalTo(snipes));
@@ -153,8 +150,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
FullTextDocument snipes = new FullTextDocument("4", "Snipes", "Wesley Trent Snipes is an actor and film producer.");
repo.save(snipes);
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"), PageRequest.of(
0, 10, Direction.ASC, "score"));
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"),
PageRequest.of(0, 10, Direction.ASC, "score"));
assertThat(page.getTotalElements(), is(4L));
assertThat(page.getContent().get(0), equalTo(snipes));
@@ -167,8 +164,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
FullTextDocument snipes = new FullTextDocument("4", "Snipes", "Wesley Trent Snipes is an actor and film producer.");
repo.save(snipes);
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"), PageRequest.of(
0, 10, Direction.ASC, "id"));
Page<FullTextDocument> page = repo.findAllBy(TextCriteria.forDefaultLanguage().matching("snipes"),
PageRequest.of(0, 10, Direction.ASC, "id"));
assertThat(page.getTotalElements(), is(4L));
assertThat(page.getContent().get(0), equalTo(PASSENGER_57));
@@ -181,8 +178,8 @@ public class MongoRepositoryTextSearchIntegrationTests {
FullTextDocument snipes = new FullTextDocument("4", "Snipes", "Wesley Trent Snipes is an actor and film producer.");
repo.save(snipes);
List<FullTextDocument> result = repo.findByNonTextIndexPropertyIsNullOrderByScoreDesc(TextCriteria
.forDefaultLanguage().matching("snipes"));
List<FullTextDocument> result = repo
.findByNonTextIndexPropertyIsNullOrderByScoreDesc(TextCriteria.forDefaultLanguage().matching("snipes"));
assertThat(result.get(0), equalTo(snipes));
}
@@ -196,7 +193,7 @@ public class MongoRepositoryTextSearchIntegrationTests {
}
private void initRepoWithDefaultDocuments() {
repo.save(Arrays.asList(PASSENGER_57, DEMOLITION_MAN, DROP_ZONE));
repo.saveAll(Arrays.asList(PASSENGER_57, DEMOLITION_MAN, DROP_ZONE));
}
@org.springframework.context.annotation.Configuration

View File

@@ -64,7 +64,7 @@ public class PersonRepositoryLazyLoadingIntegrationTests {
person.setRealFans(new ArrayList<User>(Arrays.asList(thomas)));
repository.save(person);
Person oliver = repository.findOne(person.id).get();
Person oliver = repository.findById(person.id).get();
List<User> fans = oliver.getFans();
assertProxyIsResolved(fans, false);
@@ -87,7 +87,7 @@ public class PersonRepositoryLazyLoadingIntegrationTests {
person.setRealFans(new ArrayList<User>(Arrays.asList(thomas)));
repository.save(person);
Person oliver = repository.findOne(person.id).get();
Person oliver = repository.findById(person.id).get();
List<User> realFans = oliver.getRealFans();
assertProxyIsResolved(realFans, false);
@@ -114,7 +114,7 @@ public class PersonRepositoryLazyLoadingIntegrationTests {
person.setCoworker(thomas);
repository.save(person);
Person oliver = repository.findOne(person.id).get();
Person oliver = repository.findById(person.id).get();
User coworker = oliver.getCoworker();

View File

@@ -114,7 +114,7 @@ public class ReactiveMongoRepositoryTests implements BeanClassLoaderAware, BeanF
alicia = new Person("Alicia", "Keys", 30, Sex.FEMALE);
StepVerifier.create(repository.save(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
StepVerifier.create(repository.saveAll(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
.expectNextCount(7) //
.verifyComplete();
}

View File

@@ -95,49 +95,49 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
leroi = new ReactivePerson("Leroi", "Moore", 41);
alicia = new ReactivePerson("Alicia", "Keys", 30);
StepVerifier.create(repository.save(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
StepVerifier.create(repository.saveAll(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia))) //
.expectNextCount(7) //
.verifyComplete();
}
@Test // DATAMONGO-1444
public void existsByIdShouldReturnTrueForExistingObject() {
StepVerifier.create(repository.exists(dave.id)).expectNext(true).verifyComplete();
StepVerifier.create(repository.existsById(dave.id)).expectNext(true).verifyComplete();
}
@Test // DATAMONGO-1444
public void existsByIdShouldReturnFalseForAbsentObject() {
StepVerifier.create(repository.exists("unknown")).expectNext(false).verifyComplete();
StepVerifier.create(repository.existsById("unknown")).expectNext(false).verifyComplete();
}
@Test // DATAMONGO-1444
public void existsByMonoOfIdShouldReturnTrueForExistingObject() {
StepVerifier.create(repository.exists(Mono.just(dave.id))).expectNext(true).verifyComplete();
StepVerifier.create(repository.existsById(Mono.just(dave.id))).expectNext(true).verifyComplete();
}
@Test // DATAMONGO-1444
public void existsByEmptyMonoOfIdShouldReturnEmptyMono() {
StepVerifier.create(repository.exists(Mono.empty())).verifyComplete();
StepVerifier.create(repository.existsById(Mono.empty())).verifyComplete();
}
@Test // DATAMONGO-1444
public void findOneShouldReturnObject() {
StepVerifier.create(repository.findOne(dave.id)).expectNext(dave).verifyComplete();
StepVerifier.create(repository.findById(dave.id)).expectNext(dave).verifyComplete();
}
@Test // DATAMONGO-1444
public void findOneShouldCompleteWithoutValueForAbsentObject() {
StepVerifier.create(repository.findOne("unknown")).verifyComplete();
StepVerifier.create(repository.findById("unknown")).verifyComplete();
}
@Test // DATAMONGO-1444
public void findOneByMonoOfIdShouldReturnTrueForExistingObject() {
StepVerifier.create(repository.findOne(Mono.just(dave.id))).expectNext(dave).verifyComplete();
StepVerifier.create(repository.findById(Mono.just(dave.id))).expectNext(dave).verifyComplete();
}
@Test // DATAMONGO-1444
public void findOneByEmptyMonoOfIdShouldReturnEmptyMono() {
StepVerifier.create(repository.findOne(Mono.empty())).verifyComplete();
StepVerifier.create(repository.findById(Mono.empty())).verifyComplete();
}
@Test // DATAMONGO-1444
@@ -147,17 +147,17 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
@Test // DATAMONGO-1444
public void findAllByIterableOfIdShouldReturnResults() {
StepVerifier.create(repository.findAll(Arrays.asList(dave.id, boyd.id))).expectNextCount(2).verifyComplete();
StepVerifier.create(repository.findAllById(Arrays.asList(dave.id, boyd.id))).expectNextCount(2).verifyComplete();
}
@Test // DATAMONGO-1444
public void findAllByPublisherOfIdShouldReturnResults() {
StepVerifier.create(repository.findAll(Flux.just(dave.id, boyd.id))).expectNextCount(2).verifyComplete();
StepVerifier.create(repository.findAllById(Flux.just(dave.id, boyd.id))).expectNextCount(2).verifyComplete();
}
@Test // DATAMONGO-1444
public void findAllByEmptyPublisherOfIdShouldReturnResults() {
StepVerifier.create(repository.findAll(Flux.empty())).verifyComplete();
StepVerifier.create(repository.findAllById(Flux.empty())).verifyComplete();
}
@Test // DATAMONGO-1444
@@ -239,7 +239,7 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
StepVerifier.create(repository.findByLastname("Matthews")).expectNext(oliver).verifyComplete();
StepVerifier.create(repository.findOne(dave.id)).consumeNextWith(actual -> {
StepVerifier.create(repository.findById(dave.id)).consumeNextWith(actual -> {
assertThat(actual.getFirstname(), is(equalTo(dave.getFirstname())));
assertThat(actual.getLastname(), is(equalTo(dave.getLastname())));
@@ -253,7 +253,7 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
StepVerifier.create(repository.save(person)).expectNext(person).verifyComplete();
StepVerifier.create(repository.findOne(person.id)).consumeNextWith(actual -> {
StepVerifier.create(repository.findById(person.id)).consumeNextWith(actual -> {
assertThat(actual.getFirstname(), is(equalTo(person.getFirstname())));
assertThat(actual.getLastname(), is(equalTo(person.getLastname())));
@@ -269,7 +269,7 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
oliver.setId(null);
boyd.setId(null);
StepVerifier.create(repository.save(Arrays.asList(dave, oliver, boyd))).expectNextCount(3).verifyComplete();
StepVerifier.create(repository.saveAll(Arrays.asList(dave, oliver, boyd))).expectNextCount(3).verifyComplete();
assertThat(dave.getId(), is(notNullValue()));
assertThat(oliver.getId(), is(notNullValue()));
@@ -284,12 +284,12 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
dave.setFirstname("Hello, Dave");
dave.setLastname("Bowman");
StepVerifier.create(repository.save(Arrays.asList(person, dave))).expectNextCount(2).verifyComplete();
StepVerifier.create(repository.saveAll(Arrays.asList(person, dave))).expectNextCount(2).verifyComplete();
StepVerifier.create(repository.findOne(dave.id)).expectNext(dave).verifyComplete();
StepVerifier.create(repository.findById(dave.id)).expectNext(dave).verifyComplete();
assertThat(person.id, is(notNullValue()));
StepVerifier.create(repository.findOne(person.id)).expectNext(person).verifyComplete();
StepVerifier.create(repository.findById(person.id)).expectNext(person).verifyComplete();
}
@Test // DATAMONGO-1444
@@ -301,7 +301,7 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
oliver.setId(null);
boyd.setId(null);
StepVerifier.create(repository.save(Flux.just(dave, oliver, boyd))).expectNextCount(3).verifyComplete();
StepVerifier.create(repository.saveAll(Flux.just(dave, oliver, boyd))).expectNextCount(3).verifyComplete();
assertThat(dave.getId(), is(notNullValue()));
assertThat(oliver.getId(), is(notNullValue()));
@@ -319,9 +319,9 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
@Test // DATAMONGO-1444
public void deleteByIdShouldRemoveEntity() {
StepVerifier.create(repository.delete(dave.id)).verifyComplete();
StepVerifier.create(repository.deleteById(dave.id)).verifyComplete();
StepVerifier.create(repository.findOne(dave.id)).verifyComplete();
StepVerifier.create(repository.findById(dave.id)).verifyComplete();
}
@Test // DATAMONGO-1444
@@ -329,16 +329,16 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
StepVerifier.create(repository.delete(dave)).verifyComplete();
StepVerifier.create(repository.findOne(dave.id)).verifyComplete();
StepVerifier.create(repository.findById(dave.id)).verifyComplete();
}
@Test // DATAMONGO-1444
public void deleteIterableOfEntitiesShouldRemoveEntities() {
StepVerifier.create(repository.delete(Arrays.asList(dave, boyd))).verifyComplete();
StepVerifier.create(repository.deleteAll(Arrays.asList(dave, boyd))).verifyComplete();
StepVerifier.create(repository.findOne(boyd.id)).verifyComplete();
StepVerifier.create(repository.findById(boyd.id)).verifyComplete();
StepVerifier.create(repository.findByLastname("Matthews")).expectNext(oliver).verifyComplete();
}
@@ -346,9 +346,9 @@ public class SimpleReactiveMongoRepositoryTests implements BeanClassLoaderAware,
@Test // DATAMONGO-1444
public void deletePublisherOfEntitiesShouldRemoveEntities() {
StepVerifier.create(repository.delete(Flux.just(dave, boyd))).verifyComplete();
StepVerifier.create(repository.deleteAll(Flux.just(dave, boyd))).verifyComplete();
StepVerifier.create(repository.findOne(boyd.id)).verifyComplete();
StepVerifier.create(repository.findById(boyd.id)).verifyComplete();
StepVerifier.create(repository.findByLastname("Matthews")).expectNext(oliver).verifyComplete();
}

View File

@@ -60,7 +60,7 @@ public class CdiExtensionIntegrationTests {
Person result = repository.save(person);
assertThat(result, is(notNullValue()));
assertThat(repository.findOne(person.getId()).get().getId(), is(result.getId()));
assertThat(repository.findById(person.getId()).get().getId(), is(result.getId()));
}
@Test // DATAMONGO-1017

View File

@@ -26,5 +26,5 @@ public interface CdiPersonRepository extends Repository<Person, String> {
Person save(Person person);
Optional<Person> findOne(String id);
Optional<Person> findById(String id);
}

View File

@@ -19,7 +19,6 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.Optional;
import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Range;
import org.springframework.data.domain.Sort;
@@ -96,7 +95,7 @@ class StubParameterAccessor implements MongoParameterAccessor {
* @see org.springframework.data.repository.query.ParameterAccessor#getSort()
*/
public Sort getSort() {
return null;
return Sort.unsorted();
}
/*

View File

@@ -34,8 +34,6 @@ import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.querydsl.core.types.Predicate;
/**
* Integration test for {@link QueryDslMongoRepository}.
*
@@ -68,7 +66,7 @@ public class QueryDslMongoRepositoryIntegrationTests {
person = new QPerson("person");
repository.save(Arrays.asList(oliver, dave, carter));
repository.saveAll(Arrays.asList(oliver, dave, carter));
}
@Test // DATAMONGO-1146
@@ -76,7 +74,6 @@ public class QueryDslMongoRepositoryIntegrationTests {
assertThat(repository.exists(person.firstname.eq("Dave")), is(true));
assertThat(repository.exists(person.firstname.eq("Unknown")), is(false));
assertThat(repository.exists((Predicate) null), is(true));
}
@Test // DATAMONGO-1167

View File

@@ -34,17 +34,17 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.ExampleMatcher.*;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.Address;
import org.springframework.data.mongodb.repository.Person;
import org.springframework.data.mongodb.repository.User;
import org.springframework.data.mongodb.repository.Person.Sex;
import org.springframework.data.mongodb.repository.User;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -81,7 +81,7 @@ public class SimpleMongoRepositoryTests {
leroi = new Person("Leroi", "Moore", 41);
alicia = new Person("Alicia", "Keys", 30, Sex.FEMALE);
all = repository.save(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia));
all = repository.saveAll(Arrays.asList(oliver, dave, carter, boyd, stefan, leroi, alicia));
}
@Test
@@ -92,7 +92,7 @@ public class SimpleMongoRepositoryTests {
@Test
public void findOneFromCustomCollectionName() {
Person result = repository.findOne(dave.getId()).get();
Person result = repository.findById(dave.getId()).get();
assertThat(result, is(dave));
}
@@ -107,7 +107,7 @@ public class SimpleMongoRepositoryTests {
@Test
public void deleteByIdFromCustomCollectionName() {
repository.delete(dave.getId());
repository.deleteById(dave.getId());
List<Person> result = repository.findAll();
assertThat(result, hasSize(all.size() - 1));
@@ -122,7 +122,7 @@ public class SimpleMongoRepositoryTests {
Person person1 = new Person("First1" + randomId, "Last2" + randomId, 42);
person1 = repository.insert(person1);
Person saved = repository.findOne(person1.getId()).get();
Person saved = repository.findById(person1.getId()).get();
assertThat(saved, is(equalTo(person1)));
}