diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/MongoDbFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/MongoDbFactory.java deleted file mode 100644 index 9356a9e7d..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/MongoDbFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2011-2021 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 - * - * https://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; - -import org.springframework.dao.DataAccessException; - -import com.mongodb.client.MongoDatabase; - -/** - * Interface for factories creating {@link MongoDatabase} instances. - * - * @author Mark Pollack - * @author Thomas Darimont - * @author Christoph Strobl - * @deprecated since 3.0, use {@link MongoDatabaseFactory} instead. - */ -@Deprecated -public interface MongoDbFactory extends MongoDatabaseFactory { - - /** - * Creates a default {@link MongoDatabase} instance. - * - * @return never {@literal null}. - * @throws DataAccessException - * @deprecated since 3.0. Use {@link #getMongoDatabase()} instead. - */ - @Deprecated - default MongoDatabase getDb() throws DataAccessException { - return getMongoDatabase(); - } - - /** - * Obtain a {@link MongoDatabase} instance to access the database with the given name. - * - * @param dbName must not be {@literal null} or empty. - * @return never {@literal null}. - * @throws DataAccessException - * @deprecated since 3.0. Use {@link #getMongoDatabase(String)} instead. - */ - @Deprecated - default MongoDatabase getDb(String dbName) throws DataAccessException { - return getMongoDatabase(dbName); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java index 96df484aa..ac9a608e3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoClientConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -25,9 +25,7 @@ import org.springframework.data.mongodb.core.convert.DbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; -import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; -import org.springframework.lang.Nullable; import com.mongodb.MongoClientSettings; import com.mongodb.MongoClientSettings.Builder; @@ -80,24 +78,6 @@ public abstract class AbstractMongoClientConfiguration extends MongoConfiguratio return new SimpleMongoClientDatabaseFactory(mongoClient(), getDatabaseName()); } - /** - * Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration - * class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending - * {@link AbstractMongoClientConfiguration} the base package will be considered {@code com.acme} unless the method is - * overridden to implement alternate behavior. - * - * @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for - * entities. - * @deprecated use {@link #getMappingBasePackages()} instead. - */ - @Deprecated - @Nullable - protected String getMappingBasePackage() { - - Package mappingBasePackage = getClass().getPackage(); - return mappingBasePackage == null ? null : mappingBasePackage.getName(); - } - /** * Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and * {@link #mongoMappingContext(MongoCustomConversions)}. Will get {@link #customConversions()} applied. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java index 935be9550..48ff485e1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -40,7 +40,6 @@ import org.w3c.dom.Element; * @author Christoph Strobl * @author Mark Paluch */ -@SuppressWarnings("deprecation") abstract class MongoParsingUtils { private MongoParsingUtils() {} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java index f86689669..c7b4574a3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -47,20 +47,6 @@ public class CollectionOptions { private ValidationOptions validationOptions; private @Nullable TimeSeriesOptions timeSeriesOptions; - /** - * Constructs a new CollectionOptions instance. - * - * @param size the collection size in bytes, this data space is preallocated. Can be {@literal null}. - * @param maxDocuments the maximum number of documents in the collection. Can be {@literal null}. - * @param capped true to created a "capped" collection (fixed size with auto-FIFO behavior based on insertion order), - * false otherwise. Can be {@literal null}. - * @deprecated since 2.0 please use {@link CollectionOptions#empty()} as entry point. - */ - @Deprecated - public CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped) { - this(size, maxDocuments, capped, null, ValidationOptions.none(), null); - } - private CollectionOptions(@Nullable Long size, @Nullable Long maxDocuments, @Nullable Boolean capped, @Nullable Collation collation, ValidationOptions validationOptions, @Nullable TimeSeriesOptions timeSeriesOptions) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java index cf218e581..6da2bbebf 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java @@ -337,6 +337,11 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp } private String getOrDefault(Object value, String defaultValue) { - return !StringUtils.isEmpty(value) ? value.toString() : defaultValue; + + if(value == null) { + return defaultValue; + } + String sValue = value.toString(); + return StringUtils.hasText(sValue) ? sValue : defaultValue; } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoDbFactorySupport.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoDbFactorySupport.java deleted file mode 100644 index ba530d502..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoDbFactorySupport.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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; - -import org.springframework.dao.support.PersistenceExceptionTranslator; - -/** - * Common base class for usage with both {@link com.mongodb.client.MongoClients} defining common properties such as - * database name and exception translator. - *
- * Not intended to be used directly. - * - * @author Christoph Strobl - * @author Mark Paluch - * @param Client type. - * @since 2.1 - * @see SimpleMongoClientDatabaseFactory - * @deprecated since 3.0, use {@link MongoDatabaseFactorySupport} instead. - */ -@Deprecated -public abstract class MongoDbFactorySupport extends MongoDatabaseFactorySupport { - - /** - * Create a new {@link MongoDbFactorySupport} object given {@code mongoClient}, {@code databaseName}, - * {@code mongoInstanceCreated} and {@link PersistenceExceptionTranslator}. - * - * @param mongoClient must not be {@literal null}. - * @param databaseName must not be {@literal null} or empty. - * @param mongoInstanceCreated {@literal true} if the client instance was created by a subclass of - * {@link MongoDbFactorySupport} to close the client on {@link #destroy()}. - * @param exceptionTranslator must not be {@literal null}. - */ - protected MongoDbFactorySupport(C mongoClient, String databaseName, boolean mongoInstanceCreated, - PersistenceExceptionTranslator exceptionTranslator) { - super(mongoClient, databaseName, mongoInstanceCreated, exceptionTranslator); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOperations.java index 24a3223de..8cf23c25e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOperations.java @@ -23,7 +23,6 @@ import java.util.function.Supplier; import java.util.stream.Stream; import org.bson.Document; - import org.springframework.data.geo.GeoResults; import org.springframework.data.mongodb.core.BulkOperations.BulkMode; import org.springframework.data.mongodb.core.aggregation.Aggregation; @@ -34,8 +33,6 @@ import org.springframework.data.mongodb.core.aggregation.TypedAggregation; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.data.mongodb.core.index.IndexOperations; -import org.springframework.data.mongodb.core.mapreduce.GroupBy; -import org.springframework.data.mongodb.core.mapreduce.GroupByResults; import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions; import org.springframework.data.mongodb.core.mapreduce.MapReduceResults; import org.springframework.data.mongodb.core.query.BasicQuery; @@ -431,43 +428,6 @@ public interface MongoOperations extends FluentMongoOperations { */ List findAll(Class entityClass, String collectionName); - /** - * Execute a group operation over the entire collection. The group operation entity class should match the 'shape' of - * the returned object that takes int account the initial document structure as well as any finalize functions. - * - * @param inputCollectionName the collection where the group operation will read from - * @param groupBy the conditions under which the group operation will be performed, e.g. keys, initial document, - * reduce function. - * @param entityClass The parametrized type of the returned list - * @return The results of the group operation - * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0.
- * Please use {@link #aggregate(TypedAggregation, String, Class) } with a - * {@link org.springframework.data.mongodb.core.aggregation.GroupOperation} instead. - */ - @Deprecated - GroupByResults group(String inputCollectionName, GroupBy groupBy, Class entityClass); - - /** - * Execute a group operation restricting the rows to those which match the provided Criteria. The group operation - * entity class should match the 'shape' of the returned object that takes int account the initial document structure - * as well as any finalize functions. - * - * @param criteria The criteria that restricts the row that are considered for grouping. If not specified all rows are - * considered. - * @param inputCollectionName the collection where the group operation will read from - * @param groupBy the conditions under which the group operation will be performed, e.g. keys, initial document, - * reduce function. - * @param entityClass The parametrized type of the returned list - * @return The results of the group operation - * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0.
- * Please use {@link #aggregate(TypedAggregation, String, Class) } with a - * {@link org.springframework.data.mongodb.core.aggregation.GroupOperation} and - * {@link org.springframework.data.mongodb.core.aggregation.MatchOperation} instead. - */ - @Deprecated - GroupByResults group(@Nullable Criteria criteria, String inputCollectionName, GroupBy groupBy, - Class entityClass); - /** * Execute an aggregation operation. The raw results will be mapped to the given entity class. The name of the * inputCollection is derived from the inputType of the aggregation. @@ -606,7 +566,9 @@ public interface MongoOperations extends FluentMongoOperations { * @param reduceFunction The JavaScript reduce function * @param entityClass The parametrized type of the returned list. Must not be {@literal null}. * @return The results of the map reduce operation + * @deprecated since MongoDB server version 5.0 */ + @Deprecated MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass); @@ -619,7 +581,9 @@ public interface MongoOperations extends FluentMongoOperations { * @param mapReduceOptions Options that specify detailed map-reduce behavior. * @param entityClass The parametrized type of the returned list. Must not be {@literal null}. * @return The results of the map reduce operation + * @deprecated since MongoDB server version 5.0 */ + @Deprecated MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class entityClass); @@ -633,7 +597,9 @@ public interface MongoOperations extends FluentMongoOperations { * @param reduceFunction The JavaScript reduce function * @param entityClass The parametrized type of the returned list. Must not be {@literal null}. * @return The results of the map reduce operation + * @deprecated since MongoDB server version 5.0 */ + @Deprecated MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass); @@ -647,7 +613,9 @@ public interface MongoOperations extends FluentMongoOperations { * @param mapReduceOptions Options that specify detailed map-reduce behavior * @param entityClass The parametrized type of the returned list. Must not be {@literal null}. * @return The results of the map reduce operation + * @deprecated since MongoDB server version 5.0 */ + @Deprecated MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, @Nullable MapReduceOptions mapReduceOptions, Class entityClass); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java index 8fb3310ae..84b3983a8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java @@ -29,7 +29,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bson.Document; import org.bson.conversions.Bson; - import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -87,13 +86,10 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.core.mapping.event.*; -import org.springframework.data.mongodb.core.mapreduce.GroupBy; -import org.springframework.data.mongodb.core.mapreduce.GroupByResults; import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions; import org.springframework.data.mongodb.core.mapreduce.MapReduceResults; import org.springframework.data.mongodb.core.query.BasicQuery; import org.springframework.data.mongodb.core.query.Collation; -import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Meta; import org.springframework.data.mongodb.core.query.Meta.CursorOption; import org.springframework.data.mongodb.core.query.NearQuery; @@ -386,8 +382,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } @SuppressWarnings("ConstantConditions") - protected Stream doStream(Query query, Class entityType, String collectionName, - Class returnType) { + protected Stream doStream(Query query, Class entityType, String collectionName, Class returnType) { Assert.notNull(query, "Query must not be null!"); Assert.notNull(entityType, "Entity type must not be null!"); @@ -399,8 +394,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, MongoPersistentEntity persistentEntity = mappingContext.getPersistentEntity(entityType); QueryContext queryContext = queryOperations.createQueryContext(query); - EntityProjection projection = operations.introspectProjection(returnType, - entityType); + EntityProjection projection = operations.introspectProjection(returnType, entityType); Document mappedQuery = queryContext.getMappedQuery(persistentEntity); Document mappedFields = queryContext.getMappedFields(persistentEntity, projection); @@ -570,7 +564,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @Nullable CollectionOptions collectionOptions) { Assert.notNull(collectionName, "CollectionName must not be null!"); - return doCreateCollection(collectionName, convertToDocument(collectionOptions)); + return doCreateCollection(collectionName, convertToDocument(collectionOptions, Object.class)); } @SuppressWarnings("ConstantConditions") @@ -836,8 +830,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, .withOptions(AggregationOptions.builder().collation(near.getCollation()).build()); AggregationResults results = aggregate($geoNear, collection, Document.class); - EntityProjection projection = operations.introspectProjection(returnType, - domainType); + EntityProjection projection = operations.introspectProjection(returnType, domainType); DocumentCallback> callback = new GeoNearResultDocumentCallback<>(distanceField, new ProjectingReadCallback<>(mongoConverter, projection, collection), near.getMetric()); @@ -920,8 +913,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityType); QueryContext queryContext = queryOperations.createQueryContext(query); - EntityProjection projection = operations.introspectProjection(resultType, - entityType); + EntityProjection projection = operations.introspectProjection(resultType, entityType); Document mappedQuery = queryContext.getMappedQuery(entity); Document mappedFields = queryContext.getMappedFields(entity, projection); Document mappedSort = queryContext.getMappedSort(entity); @@ -933,8 +925,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, maybeCallBeforeSave(replacement, mappedReplacement, collectionName); T saved = doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort, - queryContext.getCollation(entityType).orElse(null), entityType, mappedReplacement, options, - projection); + queryContext.getCollation(entityType).orElse(null), entityType, mappedReplacement, options, projection); if (saved != null) { maybeEmitEvent(new AfterSaveEvent<>(saved, mappedReplacement, collectionName)); @@ -1017,7 +1008,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, Assert.notNull(objectToSave, "ObjectToSave must not be null!"); - ensureNotIterable(objectToSave); + ensureNotCollectionLike(objectToSave); return insert(objectToSave, getCollectionName(ClassUtils.getUserClass(objectToSave))); } @@ -1028,21 +1019,10 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, Assert.notNull(objectToSave, "ObjectToSave must not be null!"); Assert.notNull(collectionName, "CollectionName must not be null!"); - ensureNotIterable(objectToSave); + ensureNotCollectionLike(objectToSave); return (T) doInsert(collectionName, objectToSave, this.mongoConverter); } - /** - * Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or - * {@link Iterator}. - * - * @param source can be {@literal null}. - * @deprecated since 3.2. Call {@link #ensureNotCollectionLike(Object)} instead. - */ - protected void ensureNotIterable(@Nullable Object source) { - ensureNotCollectionLike(source); - } - /** * Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or * {@link Iterator}. @@ -1646,8 +1626,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @Override public MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass) { - return mapReduce(new Query(), inputCollectionName, mapFunction, reduceFunction, - new MapReduceOptions().outputTypeInline(), entityClass); + return mapReduce(new Query(), inputCollectionName, mapFunction, reduceFunction, new MapReduceOptions(), + entityClass); } @Override @@ -1659,8 +1639,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @Override public MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction, Class entityClass) { - return mapReduce(query, inputCollectionName, mapFunction, reduceFunction, new MapReduceOptions().outputTypeInline(), - entityClass); + return mapReduce(query, inputCollectionName, mapFunction, reduceFunction, new MapReduceOptions(), entityClass); } @Override @@ -1774,66 +1753,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return mappedResults; } - public GroupByResults group(String inputCollectionName, GroupBy groupBy, Class entityClass) { - return group(null, inputCollectionName, groupBy, entityClass); - } - - public GroupByResults group(@Nullable Criteria criteria, String inputCollectionName, GroupBy groupBy, - Class entityClass) { - - Document document = groupBy.getGroupByObject(); - document.put("ns", inputCollectionName); - - if (criteria == null) { - document.put("cond", null); - } else { - document.put("cond", queryMapper.getMappedObject(criteria.getCriteriaObject(), Optional.empty())); - } - // If initial document was a JavaScript string, potentially loaded by Spring's Resource abstraction, load it and - // convert to Document - - if (document.containsKey("initial")) { - Object initialObj = document.get("initial"); - if (initialObj instanceof String) { - String initialAsString = replaceWithResourceIfNecessary((String) initialObj); - document.put("initial", Document.parse(initialAsString)); - } - } - - if (document.containsKey("$reduce")) { - document.put("$reduce", replaceWithResourceIfNecessary(ObjectUtils.nullSafeToString(document.get("$reduce")))); - } - if (document.containsKey("$keyf")) { - document.put("$keyf", replaceWithResourceIfNecessary(ObjectUtils.nullSafeToString(document.get("$keyf")))); - } - if (document.containsKey("finalize")) { - document.put("finalize", replaceWithResourceIfNecessary(ObjectUtils.nullSafeToString(document.get("finalize")))); - } - - Document commandObject = new Document("group", document); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Executing Group with Document [%s]", serializeToJsonSafely(commandObject))); - } - - Document commandResult = executeCommand(commandObject, this.readPreference); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Group command result = [%s]", commandResult)); - } - - @SuppressWarnings("unchecked") - Iterable resultSet = (Iterable) commandResult.get("retval"); - List mappedResults = new ArrayList<>(); - DocumentCallback callback = new ReadDocumentCallback<>(mongoConverter, entityClass, inputCollectionName); - - for (Document resultDocument : resultSet) { - mappedResults.add(callback.doWith(resultDocument)); - } - - return new GroupByResults<>(mappedResults, commandResult); - } - @Override public AggregationResults aggregate(TypedAggregation aggregation, Class outputType) { return aggregate(aggregation, getCollectionName(aggregation.getInputType()), outputType); @@ -2022,8 +1941,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } @SuppressWarnings("ConstantConditions") - protected Stream aggregateStream(Aggregation aggregation, String collectionName, - Class outputType, @Nullable AggregationOperationContext context) { + protected Stream aggregateStream(Aggregation aggregation, String collectionName, Class outputType, + @Nullable AggregationOperationContext context) { Assert.hasText(collectionName, "Collection name must not be null or empty!"); Assert.notNull(aggregation, "Aggregation pipeline must not be null!"); @@ -2295,8 +2214,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityClass); QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields)); - Document mappedFields = queryContext.getMappedFields(entity, - EntityProjection.nonProjecting(entityClass)); + Document mappedFields = queryContext.getMappedFields(entity, EntityProjection.nonProjecting(entityClass)); Document mappedQuery = queryContext.getMappedQuery(entity); if (LOGGER.isDebugEnabled()) { @@ -2348,8 +2266,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityClass); QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields)); - Document mappedFields = queryContext.getMappedFields(entity, - EntityProjection.nonProjecting(entityClass)); + Document mappedFields = queryContext.getMappedFields(entity, EntityProjection.nonProjecting(entityClass)); Document mappedQuery = queryContext.getMappedQuery(entity); if (LOGGER.isDebugEnabled()) { @@ -2371,8 +2288,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, Class targetClass, CursorPreparer preparer) { MongoPersistentEntity entity = mappingContext.getPersistentEntity(sourceClass); - EntityProjection projection = operations.introspectProjection(targetClass, - sourceClass); + EntityProjection projection = operations.introspectProjection(targetClass, sourceClass); QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields)); Document mappedFields = queryContext.getMappedFields(entity, projection); @@ -2387,13 +2303,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, new ProjectingReadCallback<>(mongoConverter, projection, collectionName), collectionName); } - /** * Convert given {@link CollectionOptions} to a document and take the domain type information into account when * creating a mapped schema for validation.
- * This method calls {@link #convertToDocument(CollectionOptions)} for backwards compatibility and potentially - * overwrites the validator with the mapped validator document. In the long run - * {@link #convertToDocument(CollectionOptions)} will be removed so that this one becomes the only source of truth. * * @param collectionOptions can be {@literal null}. * @param targetType must not be {@literal null}. Use {@link Object} type instead. @@ -2402,58 +2314,38 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, */ protected Document convertToDocument(@Nullable CollectionOptions collectionOptions, Class targetType) { - Document doc = convertToDocument(collectionOptions); - - if (collectionOptions != null) { - - collectionOptions.getValidationOptions().ifPresent(it -> it.getValidator() // - .ifPresent(val -> doc.put("validator", getMappedValidator(val, targetType)))); - - collectionOptions.getTimeSeriesOptions().map(operations.forType(targetType)::mapTimeSeriesOptions) - .ifPresent(it -> { - - Document timeseries = new Document("timeField", it.getTimeField()); - if (StringUtils.hasText(it.getMetaField())) { - timeseries.append("metaField", it.getMetaField()); - } - if (!Granularity.DEFAULT.equals(it.getGranularity())) { - timeseries.append("granularity", it.getGranularity().name().toLowerCase()); - } - doc.put("timeseries", timeseries); - }); + if (collectionOptions == null) { + return new Document(); } + Document doc = new Document(); + collectionOptions.getCapped().ifPresent(val -> doc.put("capped", val)); + collectionOptions.getSize().ifPresent(val -> doc.put("size", val)); + collectionOptions.getMaxDocuments().ifPresent(val -> doc.put("max", val)); + collectionOptions.getCollation().ifPresent(val -> doc.append("collation", val.toDocument())); + + collectionOptions.getValidationOptions().ifPresent(it -> { + + it.getValidationLevel().ifPresent(val -> doc.append("validationLevel", val.getValue())); + it.getValidationAction().ifPresent(val -> doc.append("validationAction", val.getValue())); + it.getValidator().ifPresent(val -> doc.append("validator", getMappedValidator(val, targetType))); + }); + + collectionOptions.getTimeSeriesOptions().map(operations.forType(targetType)::mapTimeSeriesOptions).ifPresent(it -> { + + Document timeseries = new Document("timeField", it.getTimeField()); + if (StringUtils.hasText(it.getMetaField())) { + timeseries.append("metaField", it.getMetaField()); + } + if (!Granularity.DEFAULT.equals(it.getGranularity())) { + timeseries.append("granularity", it.getGranularity().name().toLowerCase()); + } + doc.put("timeseries", timeseries); + }); + return doc; } - /** - * @param collectionOptions can be {@literal null}. - * @return never {@literal null}. - * @deprecated since 2.1 in favor of {@link #convertToDocument(CollectionOptions, Class)}. - */ - @Deprecated - protected Document convertToDocument(@Nullable CollectionOptions collectionOptions) { - - Document document = new Document(); - - if (collectionOptions != null) { - - collectionOptions.getCapped().ifPresent(val -> document.put("capped", val)); - collectionOptions.getSize().ifPresent(val -> document.put("size", val)); - collectionOptions.getMaxDocuments().ifPresent(val -> document.put("max", val)); - collectionOptions.getCollation().ifPresent(val -> document.append("collation", val.toDocument())); - - collectionOptions.getValidationOptions().ifPresent(it -> { - - it.getValidationLevel().ifPresent(val -> document.append("validationLevel", val.getValue())); - it.getValidationAction().ifPresent(val -> document.append("validationAction", val.getValue())); - it.getValidator().ifPresent(val -> document.append("validator", getMappedValidator(val, Object.class))); - }); - } - - return document; - } - Document getMappedValidator(Validator validator, Class domainType) { Document validationRules = validator.toDocument(); @@ -2467,8 +2359,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, /** * Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter. - * The first document that matches the query is returned and also removed from the collection in the database. - *
+ * The first document that matches the query is returned and also removed from the collection in the database.
* The query document is specified as a standard Document and so is the fields specification. * * @param collectionName name of the collection to retrieve the objects from @@ -2546,8 +2437,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, Document mappedSort, @Nullable com.mongodb.client.model.Collation collation, Class entityType, Document replacement, FindAndReplaceOptions options, Class resultType) { - EntityProjection projection = operations.introspectProjection(resultType, - entityType); + EntityProjection projection = operations.introspectProjection(resultType, entityType); return doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort, collation, entityType, replacement, options, projection); @@ -2575,10 +2465,12 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, Document replacement, FindAndReplaceOptions options, EntityProjection projection) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format( - "findAndReplace using query: %s fields: %s sort: %s for class: %s and replacement: %s " + "in collection: %s", - serializeToJsonSafely(mappedQuery), serializeToJsonSafely(mappedFields), serializeToJsonSafely(mappedSort), - entityType, serializeToJsonSafely(replacement), collectionName)); + LOGGER + .debug(String.format( + "findAndReplace using query: %s fields: %s sort: %s for class: %s and replacement: %s " + + "in collection: %s", + serializeToJsonSafely(mappedQuery), serializeToJsonSafely(mappedFields), + serializeToJsonSafely(mappedSort), entityType, serializeToJsonSafely(replacement), collectionName)); } return executeFindOneInternal( @@ -2771,8 +2663,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("findOne using query: %s fields: %s in db.collection: %s", - serializeToJsonSafely(query), - serializeToJsonSafely(fields.orElseGet(Document::new)), + serializeToJsonSafely(query), serializeToJsonSafely(fields.orElseGet(Document::new)), collection.getNamespace() != null ? collection.getNamespace().getFullName() : "n/a")); } @@ -3034,8 +2925,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, private final EntityProjection projection; private final String collectionName; - ProjectingReadCallback(MongoConverter mongoConverter, EntityProjection projection, - String collectionName) { + ProjectingReadCallback(MongoConverter mongoConverter, EntityProjection projection, String collectionName) { this.mongoConverter = mongoConverter; this.projection = projection; @@ -3139,7 +3029,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, cursorToUse = cursorToUse.partial(true); break; case SECONDARY_READS: - case SLAVE_OK: break; default: throw new IllegalArgumentException(String.format("%s is no supported flag.", option)); @@ -3156,8 +3045,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @Override public ReadPreference getReadPreference() { - return (query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS) - || query.getMeta().getFlags().contains(CursorOption.SLAVE_OK)) ? ReadPreference.primaryPreferred() : null; + return query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS) ? ReadPreference.primaryPreferred() + : null; } } @@ -3204,15 +3093,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } } - /** - * @deprecated since 3.1.4. Use {@link #getMongoDatabaseFactory()} instead. - * @return the {@link MongoDatabaseFactory} in use. - */ - @Deprecated - public MongoDatabaseFactory getMongoDbFactory() { - return getMongoDatabaseFactory(); - } - /** * @return the {@link MongoDatabaseFactory} in use. * @since 3.1.4 @@ -3306,8 +3186,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, /** * {@link MongoTemplate} extension bound to a specific {@link ClientSession} that is applied when interacting with the - * server through the driver API. - *
+ * server through the driver API.
* The prepare steps for {@link MongoDatabase} and {@link MongoCollection} proxy the target and invoke the desired * target method matching the actual arguments plus a {@link ClientSession}. * @@ -3325,7 +3204,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, */ SessionBoundMongoTemplate(ClientSession session, MongoTemplate that) { - super(that.getMongoDbFactory().withSession(session), that); + super(that.getMongoDatabaseFactory().withSession(session), that); this.delegate = that; this.session = session; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoClientSettingsFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoClientSettingsFactoryBean.java deleted file mode 100644 index fd7ea5ab7..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoClientSettingsFactoryBean.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2016-2021 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 - * - * https://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; - -import com.mongodb.MongoClientSettings; - -/** - * A factory bean for construction of a {@link MongoClientSettings} instance to be used with the async MongoDB driver. - * - * @author Mark Paluch - * @author Christoph Strobl - * @since 2.0 - * @deprecated since 3.0 - Use {@link MongoClientSettingsFactoryBean} instead. - */ -@Deprecated -public class ReactiveMongoClientSettingsFactoryBean extends MongoClientSettingsFactoryBean { - -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoOperations.java index 0f54bef68..904ea3f50 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -42,7 +42,6 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.mongodb.core.query.UpdateDefinition; import org.springframework.lang.Nullable; -import org.springframework.transaction.reactive.TransactionalOperator; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; @@ -58,8 +57,7 @@ import com.mongodb.reactivestreams.client.MongoCollection; *

* Implemented by {@link ReactiveMongoTemplate}. Not often used but a useful option for extensibility and testability * (as it can be easily mocked, stubbed, or be the target of a JDK proxy). Command execution using - * {@link ReactiveMongoOperations} is deferred until subscriber subscribes to the {@link Publisher}. - *
+ * {@link ReactiveMongoOperations} is deferred until subscriber subscribes to the {@link Publisher}.
* NOTE: Some operations cannot be executed within a MongoDB transaction. Please refer to the MongoDB * specific documentation to learn more about Multi * Document Transactions. @@ -120,8 +118,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono executeCommand(Document command, @Nullable ReadPreference readPreference); /** - * Executes a {@link ReactiveDatabaseCallback} translating any exceptions as necessary. - *
+ * Executes a {@link ReactiveDatabaseCallback} translating any exceptions as necessary.
* Allows for returning a result object, that is a domain object or a collection of domain objects. * * @param action callback object that specifies the MongoDB actions to perform on the passed in DB instance. Must not @@ -132,8 +129,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux execute(ReactiveDatabaseCallback action); /** - * Executes the given {@link ReactiveCollectionCallback} on the entity collection of the specified class. - *
+ * Executes the given {@link ReactiveCollectionCallback} on the entity collection of the specified class.
* Allows for returning a result object, that is a domain object or a collection of domain objects. * * @param entityClass class that determines the collection to use. Must not be {@literal null}. @@ -144,8 +140,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux execute(Class entityClass, ReactiveCollectionCallback action); /** - * Executes the given {@link ReactiveCollectionCallback} on the collection of the given name. - *
+ * Executes the given {@link ReactiveCollectionCallback} on the collection of the given name.
* Allows for returning a result object, that is a domain object or a collection of domain objects. * * @param collectionName the name of the collection that specifies which {@link MongoCollection} instance will be @@ -158,8 +153,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Obtain a {@link ClientSession session} bound instance of {@link SessionScoped} binding the {@link ClientSession} - * provided by the given {@link Supplier} to each and every command issued against MongoDB. - *
+ * provided by the given {@link Supplier} to each and every command issued against MongoDB.
* Note: It is up to the caller to manage the {@link ClientSession} lifecycle. Use * {@link ReactiveSessionScoped#execute(ReactiveSessionCallback, Consumer)} to provide a hook for processing the * {@link ClientSession} when done. @@ -177,8 +171,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Obtain a {@link ClientSession session} bound instance of {@link SessionScoped} binding a new {@link ClientSession} - * with given {@literal sessionOptions} to each and every command issued against MongoDB. - *
+ * with given {@literal sessionOptions} to each and every command issued against MongoDB.
* Note: It is up to the caller to manage the {@link ClientSession} lifecycle. Use * {@link ReactiveSessionScoped#execute(ReactiveSessionCallback, Consumer)} to provide a hook for processing the * {@link ClientSession} when done. @@ -204,8 +197,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { ReactiveSessionScoped withSession(Publisher sessionProvider); /** - * Obtain a {@link ClientSession} bound instance of {@link ReactiveMongoOperations}. - *
+ * Obtain a {@link ClientSession} bound instance of {@link ReactiveMongoOperations}.
* Note: It is up to the caller to manage the {@link ClientSession} lifecycle. * * @param session must not be {@literal null}. @@ -214,38 +206,6 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { */ ReactiveMongoOperations withSession(ClientSession session); - /** - * Initiate a new {@link ClientSession} and obtain a {@link ClientSession session} bound instance of - * {@link ReactiveSessionScoped}. Starts the transaction and adds the {@link ClientSession} to each and every command - * issued against MongoDB. - *
- * Each {@link ReactiveSessionScoped#execute(ReactiveSessionCallback) execution} initiates a new managed transaction - * that is {@link ClientSession#commitTransaction() committed} on success. Transactions are - * {@link ClientSession#abortTransaction() rolled back} upon errors. - * - * @return new instance of {@link ReactiveSessionScoped}. Never {@literal null}. - * @deprecated since 2.2. Use {@code @Transactional} or {@link TransactionalOperator}. - */ - @Deprecated - ReactiveSessionScoped inTransaction(); - - /** - * Obtain a {@link ClientSession session} bound instance of {@link ReactiveSessionScoped}, start the transaction and - * bind the {@link ClientSession} provided by the given {@link Publisher} to each and every command issued against - * MongoDB. - *
- * Each {@link ReactiveSessionScoped#execute(ReactiveSessionCallback) execution} initiates a new managed transaction - * that is {@link ClientSession#commitTransaction() committed} on success. Transactions are - * {@link ClientSession#abortTransaction() rolled back} upon errors. - * - * @param sessionProvider must not be {@literal null}. - * @return new instance of {@link ReactiveSessionScoped}. Never {@literal null}. - * @since 2.1 - * @deprecated since 2.2. Use {@code @Transactional} or {@link TransactionalOperator}. - */ - @Deprecated - ReactiveSessionScoped inTransaction(Publisher sessionProvider); - /** * Create an uncapped collection with a name based on the provided entity class. * @@ -292,8 +252,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Get a {@link MongoCollection} by name. The returned collection may not exists yet (except in local memory) and is * created on first interaction with the server. Collections can be explicitly created via * {@link #createCollection(Class)}. Please make sure to check if the collection {@link #collectionExists(Class) - * exists} first. - *
+ * exists} first.
* Translate any exceptions as necessary. * * @param collectionName name of the collection. @@ -302,8 +261,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono> getCollection(String collectionName); /** - * Check to see if a collection with a name indicated by the entity class exists. - *
+ * Check to see if a collection with a name indicated by the entity class exists.
* Translate any exceptions as necessary. * * @param entityClass class that determines the name of the collection. Must not be {@literal null}. @@ -312,8 +270,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono collectionExists(Class entityClass); /** - * Check to see if a collection with a given name exists. - *
+ * Check to see if a collection with a given name exists.
* Translate any exceptions as necessary. * * @param collectionName name of the collection. Must not be {@literal null}. @@ -322,8 +279,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono collectionExists(String collectionName); /** - * Drop the collection with the name indicated by the entity class. - *
+ * Drop the collection with the name indicated by the entity class.
* Translate any exceptions as necessary. * * @param entityClass class that determines the collection to drop/delete. Must not be {@literal null}. @@ -331,8 +287,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono dropCollection(Class entityClass); /** - * Drop the collection with the given name. - *
+ * Drop the collection with the given name.
* Translate any exceptions as necessary. * * @param collectionName name of the collection to drop/delete. @@ -340,11 +295,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono dropCollection(String collectionName); /** - * Query for a {@link Flux} of objects of type T from the collection used by the entity class. - *
+ * Query for a {@link Flux} of objects of type T from the collection used by the entity class.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way * to map objects since the test for class type is done in the client and not on the server. * @@ -354,11 +307,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux findAll(Class entityClass); /** - * Query for a {@link Flux} of objects of type T from the specified collection. - *
+ * Query for a {@link Flux} of objects of type T from the specified collection.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way * to map objects since the test for class type is done in the client and not on the server. * @@ -370,11 +321,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the - * specified type. - *
+ * specified type.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -387,11 +336,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified - * type. - *
+ * type.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -437,8 +384,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Map the results of an ad-hoc query on the collection for the entity class to a {@link Flux} of the specified type. *
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -450,11 +396,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux find(Query query, Class entityClass); /** - * Map the results of an ad-hoc query on the specified collection to a {@link Flux} of the specified type. - *
+ * Map the results of an ad-hoc query on the specified collection to a {@link Flux} of the specified type.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -565,11 +509,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux aggregate(TypedAggregation aggregation, String collectionName, Class outputType); /** - * Execute an aggregation operation. - *
+ * Execute an aggregation operation.
* The raw results will be mapped to the given entity class and are returned as stream. The name of the - * inputCollection is derived from the {@link TypedAggregation#getInputType() aggregation input type}. - *
+ * inputCollection is derived from the {@link TypedAggregation#getInputType() aggregation input type}.
* Aggregation streaming cannot be used with {@link AggregationOptions#isExplain() aggregation explain} nor with * {@link AggregationOptions#getCursorBatchSize()}. Enabling explanation mode or setting batch size cause * {@link IllegalArgumentException}. @@ -583,11 +525,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux aggregate(TypedAggregation aggregation, Class outputType); /** - * Execute an aggregation operation. - *
+ * Execute an aggregation operation.
* The raw results will be mapped to the given {@code ouputType}. The name of the inputCollection is derived from the - * {@code inputType}. - *
+ * {@code inputType}.
* Aggregation streaming cannot be used with {@link AggregationOptions#isExplain() aggregation explain} nor with * {@link AggregationOptions#getCursorBatchSize()}. Enabling explanation mode or setting batch size cause * {@link IllegalArgumentException}. @@ -603,10 +543,8 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux aggregate(Aggregation aggregation, Class inputType, Class outputType); /** - * Execute an aggregation operation. - *
- * The raw results will be mapped to the given entity class. - *
+ * Execute an aggregation operation.
+ * The raw results will be mapped to the given entity class.
* Aggregation streaming cannot be used with {@link AggregationOptions#isExplain() aggregation explain} nor with * {@link AggregationOptions#getCursorBatchSize()}. Enabling explanation mode or setting batch size cause * {@link IllegalArgumentException}. @@ -901,10 +839,8 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Map the results of an ad-hoc query on the collection for the entity type to a single instance of an object of the * specified type. The first document that matches the query is returned and also removed from the collection in the - * database. - *
- * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. - *
+ * database.
+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -920,8 +856,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * type. The first document that matches the query is returned and also removed from the collection in the database. *
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -939,8 +874,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * NOTE: Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct * influence on the resulting number of documents found as those values are passed on to the server and potentially * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to - * count all matches. - *
+ * count all matches.
* This method uses an * {@link com.mongodb.reactivestreams.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions) * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees @@ -961,8 +895,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * NOTE: Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct * influence on the resulting number of documents found as those values are passed on to the server and potentially * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to - * count all matches. - *
+ * count all matches.
* This method uses an * {@link com.mongodb.reactivestreams.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions) * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees @@ -982,8 +915,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * NOTE: Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct * influence on the resulting number of documents found as those values are passed on to the server and potentially * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to - * count all matches. - *
+ * count all matches.
* This method uses an * {@link com.mongodb.reactivestreams.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions) * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees @@ -1000,8 +932,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Estimate the number of documents, in the collection {@link #getCollectionName(Class) identified by the given type}, - * based on collection statistics. - *
+ * based on collection statistics.
* Please make sure to read the MongoDB reference documentation about limitations on eg. sharded cluster or inside * transactions. * @@ -1016,8 +947,7 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { } /** - * Estimate the number of documents in the given collection based on collection statistics. - *
+ * Estimate the number of documents in the given collection based on collection statistics.
* Please make sure to read the MongoDB reference documentation about limitations on eg. sharded cluster or inside * transactions. * @@ -1028,16 +958,13 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono estimatedCount(String collectionName); /** - * Insert the object into the collection for the entity type of the object to save. - *
- * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. - *
+ * Insert the object into the collection for the entity type of the object to save.
+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See * Spring's - * Type Conversion" for more details. - *
+ * Type Conversion" for more details.
* Insert is used to initially store the object into the database. To update an existing object use the save method. *
* The {@code objectToSave} must not be collection-like. @@ -1049,11 +976,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Mono insert(T objectToSave); /** - * Insert the object into the specified collection. - *
+ * Insert the object into the specified collection.
* The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* Insert is used to initially store the object into the database. To update an existing object use the save method. *
* The {@code objectToSave} must not be collection-like. @@ -1093,16 +1018,13 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { Flux insertAll(Collection objectsToSave); /** - * Insert the object into the collection for the entity type of the object to save. - *
- * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. - *
+ * Insert the object into the collection for the entity type of the object to save.
+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See * Spring's - * Type Conversion" for more details. - *
+ * Type Conversion" for more details.
* Insert is used to initially store the object into the database. To update an existing object use the save method. * * @param objectToSave the object to store in the collection. Must not be {@literal null}. @@ -1139,17 +1061,14 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Save the object to the collection for the entity type of the object to save. This will perform an insert if the - * object is not already present, that is an 'upsert'. - *
+ * object is not already present, that is an 'upsert'.
* The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See * Spring's - * Type Conversion" for more details. - *
+ * Type Conversion" for more details.
* The {@code objectToSave} must not be collection-like. * * @param objectToSave the object to store in the collection. Must not be {@literal null}. @@ -1160,15 +1079,14 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Save the object to the specified collection. This will perform an insert if the object is not already present, that - * is an 'upsert'. - *
+ * is an 'upsert'.
* The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your - * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. - * See Spring's Type Conversion for more details. + * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See + * Spring's Type + * Conversion for more details. * * @param objectToSave the object to store in the collection. Must not be {@literal null}. * @param collectionName name of the collection to store the object in. Must not be {@literal null}. @@ -1179,15 +1097,14 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Save the object to the collection for the entity type of the object to save. This will perform an insert if the - * object is not already present, that is an 'upsert'. - *
+ * object is not already present, that is an 'upsert'.
* The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your - * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. - * See Spring's Type Conversion for more details. + * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See + * Spring's Type + * Conversion for more details. * * @param objectToSave the object to store in the collection. Must not be {@literal null}. * @return the saved object. @@ -1196,15 +1113,14 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Save the object to the specified collection. This will perform an insert if the object is not already present, that - * is an 'upsert'. - *
+ * is an 'upsert'.
* The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your - * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. - * See Spring's Type Conversion for more details. + * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See + * Spring's Type + * Conversion for more details. * * @param objectToSave the object to store in the collReactiveMongoOperationsection. Must not be {@literal null}. * @param collectionName name of the collection to store the object in. Must not be {@literal null}. @@ -1477,11 +1393,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Map the results of an ad-hoc query on the collection for the entity class to a stream of objects of the specified * type. The stream uses a {@link com.mongodb.CursorType#TailableAwait tailable} cursor that may be an infinite * stream. The stream will not be completed unless the {@link org.reactivestreams.Subscription} is - * {@link Subscription#cancel() canceled}. - *
+ * {@link Subscription#cancel() canceled}.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -1496,11 +1410,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Map the results of an ad-hoc query on the collection for the entity class to a stream of objects of the specified * type. The stream uses a {@link com.mongodb.CursorType#TailableAwait tailable} cursor that may be an infinite * stream. The stream will not be completed unless the {@link org.reactivestreams.Subscription} is - * {@link Subscription#cancel() canceled}. - *
+ * {@link Subscription#cancel() canceled}.
* The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless - * configured otherwise, an instance of {@link MappingMongoConverter} will be used. - *
+ * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
* The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more * feature rich {@link Query}. * @@ -1516,11 +1428,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Subscribe to a MongoDB Change Stream for all events in * the configured default database via the reactive infrastructure. Use the optional provided {@link Aggregation} to * filter events. The stream will not be completed unless the {@link org.reactivestreams.Subscription} is - * {@link Subscription#cancel() canceled}. - *
+ * {@link Subscription#cancel() canceled}.
* The {@link ChangeStreamEvent#getBody()} is mapped to the {@literal resultType} while the - * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload. - *
+ * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload.
* Use {@link ChangeStreamOptions} to set arguments like {@link ChangeStreamOptions#getResumeToken() the resumseToken} * for resuming change streams. * @@ -1540,11 +1450,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * Subscribe to a MongoDB Change Stream for all events in * the given collection via the reactive infrastructure. Use the optional provided {@link Aggregation} to filter * events. The stream will not be completed unless the {@link org.reactivestreams.Subscription} is - * {@link Subscription#cancel() canceled}. - *
+ * {@link Subscription#cancel() canceled}.
* The {@link ChangeStreamEvent#getBody()} is mapped to the {@literal resultType} while the - * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload. - *
+ * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload.
* Use {@link ChangeStreamOptions} to set arguments like {@link ChangeStreamOptions#getResumeToken() the resumseToken} * for resuming change streams. * @@ -1565,11 +1473,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { /** * Subscribe to a MongoDB Change Stream via the reactive * infrastructure. Use the optional provided {@link Aggregation} to filter events. The stream will not be completed - * unless the {@link org.reactivestreams.Subscription} is {@link Subscription#cancel() canceled}. - *
+ * unless the {@link org.reactivestreams.Subscription} is {@link Subscription#cancel() canceled}.
* The {@link ChangeStreamEvent#getBody()} is mapped to the {@literal resultType} while the - * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload. - *
+ * {@link ChangeStreamEvent#getRaw()} contains the unmodified payload.
* Use {@link ChangeStreamOptions} to set arguments like {@link ChangeStreamOptions#getResumeToken() the resumseToken} * for resuming change streams. * @@ -1599,7 +1505,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * @param options additional options like output collection. Must not be {@literal null}. * @return a {@link Flux} emitting the result document sequence. Never {@literal null}. * @since 2.1 + * @deprecated since MongoDB server version 5.0 */ + @Deprecated Flux mapReduce(Query filterQuery, Class domainType, Class resultType, String mapFunction, String reduceFunction, MapReduceOptions options); @@ -1617,7 +1525,9 @@ public interface ReactiveMongoOperations extends ReactiveFluentMongoOperations { * @param options additional options like output collection. Must not be {@literal null}. * @return a {@link Flux} emitting the result document sequence. Never {@literal null}. * @since 2.1 + * @deprecated since MongoDB server version 5.0 */ + @Deprecated Flux mapReduce(Query filterQuery, Class domainType, String inputCollectionName, Class resultType, String mapFunction, String reduceFunction, MapReduceOptions options); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java index 94364ddc2..b37360ab9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core; import static org.springframework.data.mongodb.core.query.SerializationUtils.*; -import org.springframework.data.projection.EntityProjection; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.function.Tuple2; @@ -45,7 +44,6 @@ import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; - import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -114,6 +112,7 @@ import org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter; import org.springframework.data.mongodb.core.timeseries.Granularity; import org.springframework.data.mongodb.core.validation.Validator; import org.springframework.data.mongodb.util.BsonUtils; +import org.springframework.data.projection.EntityProjection; import org.springframework.data.util.Optionals; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -351,8 +350,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati /** * Set the {@link ReactiveEntityCallbacks} instance to use when invoking * {@link org.springframework.data.mapping.callback.EntityCallback callbacks} like the - * {@link ReactiveBeforeSaveCallback}. - *
+ * {@link ReactiveBeforeSaveCallback}.
* Overrides potentially existing {@link ReactiveEntityCallbacks}. * * @param entityCallbacks must not be {@literal null}. @@ -480,39 +478,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati this.sessionSynchronization = sessionSynchronization; } - @Override - public ReactiveSessionScoped inTransaction() { - return inTransaction( - mongoDatabaseFactory.getSession(ClientSessionOptions.builder().causallyConsistent(true).build())); - } - - @Override - public ReactiveSessionScoped inTransaction(Publisher sessionProvider) { - - Mono cachedSession = Mono.from(sessionProvider).cache(); - - return new ReactiveSessionScoped() { - - @Override - public Flux execute(ReactiveSessionCallback action, Consumer doFinally) { - - return cachedSession.flatMapMany(session -> { - - if (!session.hasActiveTransaction()) { - session.startTransaction(); - } - - return Flux.usingWhen(Mono.just(session), // - s -> ReactiveMongoTemplate.this.withSession(action, s), // - ClientSession::commitTransaction, // - (sess, err) -> sess.abortTransaction(), // - ClientSession::commitTransaction) // - .doFinally(signalType -> doFinally.accept(session)); - }); - } - }; - } - private Flux withSession(ReactiveSessionCallback action, ClientSession session) { ReactiveSessionBoundMongoTemplate operations = new ReactiveSessionBoundMongoTemplate(session, @@ -888,8 +853,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati String collection = StringUtils.hasText(collectionName) ? collectionName : getCollectionName(entityClass); String distanceField = operations.nearQueryDistanceFieldName(entityClass); - EntityProjection projection = operations.introspectProjection(returnType, - entityClass); + EntityProjection projection = operations.introspectProjection(returnType, entityClass); GeoNearResultDocumentCallback callback = new GeoNearResultDocumentCallback<>(distanceField, new ProjectingReadCallback<>(mongoConverter, projection, collection), near.getMetric()); @@ -951,8 +915,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityType); QueryContext queryContext = queryOperations.createQueryContext(query); - EntityProjection projection = operations.introspectProjection(resultType, - entityType); + EntityProjection projection = operations.introspectProjection(resultType, entityType); Document mappedQuery = queryContext.getMappedQuery(entity); Document mappedFields = queryContext.getMappedFields(entity, projection); @@ -975,8 +938,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati }).flatMap(it -> { Mono afterFindAndReplace = doFindAndReplace(it.getCollection(), mappedQuery, mappedFields, mappedSort, - queryContext.getCollation(entityType).orElse(null), entityType, it.getTarget(), options, - projection); + queryContext.getCollation(entityType).orElse(null), entityType, it.getTarget(), options, projection); return afterFindAndReplace.flatMap(saved -> { maybeEmitEvent(new AfterSaveEvent<>(saved, it.getTarget(), it.getCollection())); return maybeCallAfterSave(saved, it.getTarget(), it.getCollection()); @@ -1078,7 +1040,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati Assert.notNull(objectToSave, "Object to insert must not be null!"); - ensureNotIterable(objectToSave); + ensureNotCollectionLike(objectToSave); return insert(objectToSave, getCollectionName(ClassUtils.getUserClass(objectToSave))); } @@ -1086,7 +1048,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati Assert.notNull(objectToSave, "Object to insert must not be null!"); - ensureNotIterable(objectToSave); + ensureNotCollectionLike(objectToSave); return doInsert(collectionName, objectToSave, this.mongoConverter); } @@ -1988,8 +1950,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati QueryContext queryContext = queryOperations .createQueryContext(new BasicQuery(query, fields != null ? fields : new Document())); - Document mappedFields = queryContext.getMappedFields(entity, - EntityProjection.nonProjecting(entityClass)); + Document mappedFields = queryContext.getMappedFields(entity, EntityProjection.nonProjecting(entityClass)); Document mappedQuery = queryContext.getMappedQuery(entity); if (LOGGER.isDebugEnabled()) { @@ -2041,8 +2002,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityClass); QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields)); - Document mappedFields = queryContext.getMappedFields(entity, - EntityProjection.nonProjecting(entityClass)); + Document mappedFields = queryContext.getMappedFields(entity, EntityProjection.nonProjecting(entityClass)); Document mappedQuery = queryContext.getMappedQuery(entity); if (LOGGER.isDebugEnabled()) { @@ -2064,8 +2024,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati Class targetClass, FindPublisherPreparer preparer) { MongoPersistentEntity entity = mappingContext.getPersistentEntity(sourceClass); - EntityProjection projection = operations.introspectProjection(targetClass, - sourceClass); + EntityProjection projection = operations.introspectProjection(targetClass, sourceClass); QueryContext queryContext = queryOperations.createQueryContext(new BasicQuery(query, fields)); Document mappedFields = queryContext.getMappedFields(entity, projection); @@ -2140,8 +2099,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati /** * Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter. - * The first document that matches the query is returned and also removed from the collection in the database. - *
+ * The first document that matches the query is returned and also removed from the collection in the database.
* The query document is specified as a standard Document and so is the fields specification. * * @param collectionName name of the collection to retrieve the objects from @@ -2212,8 +2170,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati Document mappedSort, com.mongodb.client.model.Collation collation, Class entityType, Document replacement, FindAndReplaceOptions options, Class resultType) { - EntityProjection projection = operations.introspectProjection(resultType, - entityType); + EntityProjection projection = operations.introspectProjection(resultType, entityType); return doFindAndReplace(collectionName, mappedQuery, mappedFields, mappedSort, collation, entityType, replacement, options, projection); @@ -2311,17 +2268,6 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati } } - /** - * Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or - * {@link Iterator}. - * - * @param source can be {@literal null}. - * @deprecated since 3.2. Call {@link #ensureNotCollectionLike(Object)} instead. - */ - protected void ensureNotIterable(@Nullable Object source) { - ensureNotCollectionLike(source); - } - /** * Ensure the given {@literal source} is not an {@link java.lang.reflect.Array}, {@link Collection} or * {@link Iterator}. @@ -2832,8 +2778,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati private final EntityProjection projection; private final String collectionName; - ProjectingReadCallback(MongoConverter reader, EntityProjection projection, - String collectionName) { + ProjectingReadCallback(MongoConverter reader, EntityProjection projection, String collectionName) { this.reader = reader; this.projection = projection; this.collectionName = collectionName; @@ -2987,8 +2932,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati @Override public ReadPreference getReadPreference() { - return (query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS) - || query.getMeta().getFlags().contains(CursorOption.SLAVE_OK)) ? ReadPreference.primaryPreferred() : null; + return query.getMeta().getFlags().contains(CursorOption.SECONDARY_READS) ? ReadPreference.primaryPreferred() + : null; } } @@ -3010,8 +2955,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati /** * {@link MongoTemplate} extension bound to a specific {@link ClientSession} that is applied when interacting with the - * server through the driver API. - *
+ * server through the driver API.
* The prepare steps for {@link MongoDatabase} and {@link MongoCollection} proxy the target and invoke the desired * target method matching the actual arguments plus a {@link ClientSession}. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoClientDbFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoClientDbFactory.java deleted file mode 100644 index 3ce3ce577..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoClientDbFactory.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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; - -import com.mongodb.ConnectionString; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.MongoDatabase; - -/** - * Factory to create {@link MongoDatabase} instances from a {@link MongoClient} instance. - * - * @author Christoph Strobl - * @since 2.1 - * @deprecated since 3.0, use {@link SimpleMongoClientDatabaseFactory} instead. - */ -@Deprecated -public class SimpleMongoClientDbFactory extends SimpleMongoClientDatabaseFactory { - - /** - * Creates a new {@link SimpleMongoClientDbFactory} instance for the given {@code connectionString}. - * - * @param connectionString connection coordinates for a database connection. Must contain a database name and must not - * be {@literal null} or empty. - * @see MongoDB Connection String reference - */ - public SimpleMongoClientDbFactory(String connectionString) { - this(new ConnectionString(connectionString)); - } - - /** - * Creates a new {@link SimpleMongoClientDbFactory} instance from the given {@link MongoClient}. - * - * @param connectionString connection coordinates for a database connection. Must contain also a database name and not - * be {@literal null}. - */ - public SimpleMongoClientDbFactory(ConnectionString connectionString) { - this(MongoClients.create(connectionString), connectionString.getDatabase(), true); - } - - /** - * Creates a new {@link SimpleMongoClientDbFactory} instance from the given {@link MongoClient}. - * - * @param mongoClient must not be {@literal null}. - * @param databaseName must not be {@literal null} or empty. - */ - public SimpleMongoClientDbFactory(MongoClient mongoClient, String databaseName) { - this(mongoClient, databaseName, false); - } - - /** - * Creates a new {@link SimpleMongoClientDbFactory} instance from the given {@link MongoClient}. - * - * @param mongoClient must not be {@literal null}. - * @param databaseName must not be {@literal null} or empty. - * @param mongoInstanceCreated - */ - private SimpleMongoClientDbFactory(MongoClient mongoClient, String databaseName, boolean mongoInstanceCreated) { - super(mongoClient, databaseName, mongoInstanceCreated); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java index f1e759452..f8e56e110 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -226,8 +226,7 @@ public class Aggregation { } /** - * Obtain an {@link AddFieldsOperationBuilder builder} instance to create a new {@link AddFieldsOperation}. - *
+ * Obtain an {@link AddFieldsOperationBuilder builder} instance to create a new {@link AddFieldsOperation}.
* Starting in version 4.2, MongoDB adds a new aggregation pipeline stage {@link AggregationUpdate#set $set} that is * an alias for {@code $addFields}. * @@ -435,18 +434,6 @@ public class Aggregation { return new SortByCountOperation(groupAndSortExpression); } - /** - * Creates a new {@link SkipOperation} skipping the given number of elements. - * - * @param elementsToSkip must not be less than zero. - * @return new instance of {@link SkipOperation}. - * @deprecated prepare to get this one removed in favor of {@link #skip(long)}. - */ - @Deprecated - public static SkipOperation skip(int elementsToSkip) { - return new SkipOperation(elementsToSkip); - } - /** * Creates a new {@link SkipOperation} skipping the given number of elements. * @@ -725,8 +712,7 @@ public class Aggregation { } /** - * Converts this {@link Aggregation} specification to a {@link Document}. - *
+ * Converts this {@link Aggregation} specification to a {@link Document}.
* MongoDB requires as of 3.6 cursor-based aggregation. Use {@link #toPipeline(AggregationOperationContext)} to render * an aggregation pipeline. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationFunctionExpressions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationFunctionExpressions.java deleted file mode 100644 index cf1848d69..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationFunctionExpressions.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2015-2021 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 - * - * https://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.aggregation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.bson.Document; -import org.springframework.util.Assert; - -/** - * An enum of supported {@link AggregationExpression}s in aggregation pipeline stages. - * - * @author Thomas Darimont - * @author Oliver Gierke - * @author Christoph Strobl - * @author Mark Paluch - * @since 1.7 - * @deprecated since 1.10. Please use {@link ArithmeticOperators} and {@link ComparisonOperators} instead. - */ -@Deprecated -public enum AggregationFunctionExpressions { - - SIZE, CMP, EQ, GT, GTE, LT, LTE, NE, SUBTRACT, ADD, MULTIPLY; - - /** - * Returns an {@link AggregationExpression} build from the current {@link Enum} name and the given parameters. - * - * @param parameters must not be {@literal null} - * @return new instance of {@link AggregationExpression}. - */ - public AggregationExpression of(Object... parameters) { - - Assert.notNull(parameters, "Parameters must not be null!"); - return new FunctionExpression(name().toLowerCase(), parameters); - } - - /** - * An {@link AggregationExpression} representing a function call. - * - * @author Thomas Darimont - * @author Oliver Gierke - * @since 1.7 - */ - static class FunctionExpression implements AggregationExpression { - - private final String name; - private final List values; - - /** - * Creates a new {@link FunctionExpression} for the given name and values. - * - * @param name must not be {@literal null} or empty. - * @param values must not be {@literal null}. - */ - public FunctionExpression(String name, Object[] values) { - - Assert.hasText(name, "Name must not be null!"); - Assert.notNull(values, "Values must not be null!"); - - this.name = name; - this.values = Arrays.asList(values); - } - - @Override - public Document toDocument(AggregationOperationContext context) { - - List args = new ArrayList(values.size()); - - for (Object value : values) { - args.add(unpack(value, context)); - } - - return new Document("$" + name, args); - } - - private static Object unpack(Object value, AggregationOperationContext context) { - - if (value instanceof AggregationExpression) { - return ((AggregationExpression) value).toDocument(context); - } - - if (value instanceof Field) { - return context.getReference((Field) value).toString(); - } - - return value; - } - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/DateOperators.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/DateOperators.java index d1e45a8b9..c6a4a243f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/DateOperators.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/DateOperators.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -91,8 +91,7 @@ public class DateOperators { } /** - * Take the given value as date. - *
+ * Take the given value as date.
* This can be one of: *
    *
  • {@link java.util.Date}
  • @@ -190,7 +189,7 @@ public class DateOperators { * representing an Olson Timezone Identifier or UTC Offset. * * @param value the plain timezone {@link String}, a {@link Field} holding the timezone or an - * {@link AggregationExpression} resulting in the timezone. + * {@link AggregationExpression} resulting in the timezone. * @return new instance of {@link Timezone}. */ public static Timezone valueOf(Object value) { @@ -333,8 +332,7 @@ public class DateOperators { } /** - * Creates new {@link DateOperatorFactory} for given {@code value} that resolves to a Date. - *
    + * Creates new {@link DateOperatorFactory} for given {@code value} that resolves to a Date.
    *
      *
    • {@link java.util.Date}
    • *
    • {@link java.util.Calendar}
    • @@ -2088,20 +2086,6 @@ public class DateOperators { return second(expression); } - /** - * Set the {@literal millisecond} to the given value which must resolve to a value in range {@code 0 - 999}. Can be - * a simple value, {@link Field field reference} or {@link AggregationExpression expression}. - * - * @param millisecond must not be {@literal null}. - * @return new instance. - * @throws IllegalArgumentException if given {@literal millisecond} is {@literal null} - * @deprecated since 3.2, use {@link #millisecond(Object)} instead. - */ - @Deprecated - default T milliseconds(Object millisecond) { - return millisecond(millisecond); - } - /** * Set the {@literal millisecond} to the given value which must resolve to a value in range {@code 0 - 999}. Can be * a simple value, {@link Field field reference} or {@link AggregationExpression expression}. @@ -2113,19 +2097,6 @@ public class DateOperators { */ T millisecond(Object millisecond); - /** - * Set the {@literal millisecond} to the value resolved by following the given {@link Field field reference}. - * - * @param fieldReference must not be {@literal null}. - * @return new instance. - * @throws IllegalArgumentException if given {@literal fieldReference} is {@literal null}. - * @deprecated since 3.2,use {@link #millisecondOf(String)} instead. - */ - @Deprecated - default T millisecondsOf(String fieldReference) { - return millisecondOf(fieldReference); - } - /** * Set the {@literal millisecond} to the value resolved by following the given {@link Field field reference}. * @@ -2135,20 +2106,7 @@ public class DateOperators { * @since 3.2 */ default T millisecondOf(String fieldReference) { - return milliseconds(Fields.field(fieldReference)); - } - - /** - * Set the {@literal millisecond} to the result of the given {@link AggregationExpression expression}. - * - * @param expression must not be {@literal null}. - * @return new instance. - * @throws IllegalArgumentException if given {@literal expression} is {@literal null}. - * @deprecated since 3.2, use {@link #millisecondOf(AggregationExpression)} instead. - */ - @Deprecated - default T millisecondsOf(AggregationExpression expression) { - return millisecondOf(expression); + return millisecond(Fields.field(fieldReference)); } /** @@ -2160,7 +2118,7 @@ public class DateOperators { * @since 3.2 */ default T millisecondOf(AggregationExpression expression) { - return milliseconds(expression); + return millisecond(expression); } } @@ -2171,7 +2129,7 @@ public class DateOperators { * @author Matt Morrissette * @author Christoph Strobl * @see https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/ + * "https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/">https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/ * @since 2.1 */ public static class DateFromParts extends TimezonedDateAggregationExpression implements DateParts { @@ -2346,7 +2304,7 @@ public class DateOperators { * @author Matt Morrissette * @author Christoph Strobl * @see https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/ + * "https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/">https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromParts/ * @since 2.1 */ public static class IsoDateFromParts extends TimezonedDateAggregationExpression @@ -2522,7 +2480,7 @@ public class DateOperators { * @author Matt Morrissette * @author Christoph Strobl * @see https://docs.mongodb.com/manual/reference/operator/aggregation/dateToParts/ + * "https://docs.mongodb.com/manual/reference/operator/aggregation/dateToParts/">https://docs.mongodb.com/manual/reference/operator/aggregation/dateToParts/ * @since 2.1 */ public static class DateToParts extends TimezonedDateAggregationExpression { @@ -2603,7 +2561,7 @@ public class DateOperators { * @author Matt Morrissette * @author Christoph Strobl * @see https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/ + * "https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/">https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/ * @since 2.1 */ public static class DateFromString extends TimezonedDateAggregationExpression { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/CustomConversions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/CustomConversions.java deleted file mode 100644 index 91380271b..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/CustomConversions.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2011-2021 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 - * - * https://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 java.util.ArrayList; -import java.util.List; - -import org.springframework.data.mapping.model.SimpleTypeHolder; - -/** - * Value object to capture custom conversion. That is essentially a {@link List} of converters and some additional logic - * around them. The converters are pretty much builds up two sets of types which Mongo basic types {@see #MONGO_TYPES} - * can be converted into and from. These types will be considered simple ones (which means they neither need deeper - * inspection nor nested conversion. Thus the {@link CustomConversions} also act as factory for {@link SimpleTypeHolder} - * . - * - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - * @author Mark Paluch - * @deprecated since 2.0, use {@link MongoCustomConversions}. - */ -@Deprecated -public class CustomConversions extends MongoCustomConversions { - - /** - * Creates an empty {@link CustomConversions} object. - */ - CustomConversions() { - this(new ArrayList<>()); - } - - /** - * Creates a new {@link CustomConversions} instance registering the given converters. - * - * @param converters must not be {@literal null}. - */ - public CustomConversions(List converters) { - super(converters); - } - -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java index ed9e89176..f031c22b6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java @@ -1438,20 +1438,6 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App return getPotentiallyConvertedSimpleRead(items, targetType.getType()); } - /** - * Reads the given {@link Document} into a {@link Map}. will recursively resolve nested {@link Map}s as well. - * - * @param type the {@link Map} {@link TypeInformation} to be used to unmarshall this {@link Document}. - * @param bson must not be {@literal null} - * @param path must not be {@literal null} - * @return - * @deprecated since 3.2. Use {@link #readMap(ConversionContext, Bson, TypeInformation)} instead. - */ - @Deprecated - protected Map readMap(TypeInformation type, Bson bson, ObjectPath path) { - return readMap(getConversionContext(path), bson, type); - } - /** * Reads the given {@link Document} into a {@link Map}. will recursively resolve nested {@link Map}s as well. Can be * overridden by subclasses. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java index c6c8e46a7..3da4502ff 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2022 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. @@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core.convert; import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.util.Lazy; @@ -90,38 +89,6 @@ class ObjectPath { return new ObjectPath(this, object, id, Lazy.of(entity::getCollection)); } - /** - * Returns the object with the given id and stored in the given collection if it's contained in the - * {@link ObjectPath}. - * - * @param id must not be {@literal null}. - * @param collection must not be {@literal null} or empty. - * @return - * @deprecated use {@link #getPathItem(Object, String, Class)}. - */ - @Nullable - @Deprecated - Object getPathItem(Object id, String collection) { - - Assert.notNull(id, "Id must not be null!"); - Assert.hasText(collection, "Collection name must not be null!"); - - for (ObjectPath current = this; current != null; current = current.parent) { - - Object object = current.getObject(); - - if (object == null || current.getIdValue() == null) { - continue; - } - - if (collection.equals(current.getCollection()) && id.equals(current.getIdValue())) { - return object; - } - } - - return null; - } - /** * Get the object with given {@literal id}, stored in the {@literal collection} that is assignable to the given * {@literal type} or {@literal null} if no match found. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java index dbedae575..74cc7c3d4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java @@ -27,7 +27,6 @@ import org.bson.BsonValue; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; - import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.converter.Converter; import org.springframework.data.annotation.Reference; @@ -119,7 +118,6 @@ public class QueryMapper { * @param entity can be {@literal null}. * @return */ - @SuppressWarnings("deprecation") public Document getMappedObject(Bson query, @Nullable MongoPersistentEntity entity) { if (isNestedKeyword(query)) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/CompoundIndex.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/CompoundIndex.java index 2130df2b5..138801506 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/CompoundIndex.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/CompoundIndex.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -23,8 +23,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Mark a class to use compound indexes. - *
      + * Mark a class to use compound indexes.
      *

      * NOTE: This annotation is repeatable according to Java 8 conventions using {@link CompoundIndexes#value()} as * container. @@ -79,15 +78,6 @@ public @interface CompoundIndex { */ String def() default ""; - /** - * It does not actually make sense to use that attribute as the direction has to be defined in the {@link #def()} - * attribute actually. - * - * @return {@link IndexDirection#ASCENDING} by default. - */ - @Deprecated - IndexDirection direction() default IndexDirection.ASCENDING; - /** * @return {@literal false} by default. * @see https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping - * @deprecated since 2.1. No longer supported by MongoDB as of server version 3.0. - */ - @Deprecated - boolean dropDups() default false; - /** * Index name of the index to be created either as plain value or as * {@link org.springframework.expression.spel.standard.SpelExpression template expression}.
      diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeoSpatialIndexed.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeoSpatialIndexed.java index 6ece16125..976f2847a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeoSpatialIndexed.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeoSpatialIndexed.java @@ -119,7 +119,9 @@ public @interface GeoSpatialIndexed { * * @since 1.4 * @return {@literal 1.0} by default. + * @deprecated since MongoDB server version 4.4 */ + @Deprecated double bucketSize() default 1.0; /** diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java index b25a91a41..e2bd50e68 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java @@ -109,7 +109,9 @@ public class GeospatialIndex implements IndexDefinition { /** * @param bucketSize * @return this. + * @deprecated since MongoDB server version 4.4 */ + @Deprecated public GeospatialIndex withBucketSize(double bucketSize) { this.bucketSize = bucketSize; return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java index 30eb4ea79..ee0ed2cff 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -37,14 +37,6 @@ import org.springframework.util.StringUtils; @SuppressWarnings("deprecation") public class Index implements IndexDefinition { - /** - * @deprecated since 2.1. No longer supported by MongoDB as of server version 3.0. - */ - @Deprecated - public enum Duplicates { - RETAIN - } - private final Map fieldSpec = new LinkedHashMap(); private @Nullable String name; private boolean unique = false; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Indexed.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Indexed.java index 31a21e09d..3b41a4d80 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Indexed.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Indexed.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -62,15 +62,6 @@ public @interface Indexed { */ boolean sparse() default false; - /** - * @return {@literal false} by default. - * @see https://docs.mongodb.org/manual/core/index-creation/#index-creation-duplicate-dropping - * @deprecated since 2.1. No longer supported by MongoDB as of server version 3.0. - */ - @Deprecated - boolean dropDups() default false; - /** * Index name either as plain value or as {@link org.springframework.expression.spel.standard.SpelExpression template * expression}.
      diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListener.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListener.java deleted file mode 100644 index 4bde2b7ba..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2012-2021 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 - * - * https://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.mapping.event; - -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.context.ApplicationListener; -import org.springframework.core.Ordered; -import org.springframework.data.auditing.AuditingHandler; -import org.springframework.data.auditing.IsNewAwareAuditingHandler; -import org.springframework.data.mapping.context.MappingContext; -import org.springframework.util.Assert; - -/** - * Event listener to populate auditing related fields on an entity about to be saved. - * - * @author Oliver Gierke - * @author Thomas Darimont - * @deprecated since 2.2, use {@link AuditingEntityCallback}. - */ -@Deprecated -public class AuditingEventListener implements ApplicationListener>, Ordered { - - private final ObjectFactory auditingHandlerFactory; - - /** - * Creates a new {@link AuditingEventListener} using the given {@link MappingContext} and {@link AuditingHandler} - * provided by the given {@link ObjectFactory}. - * - * @param auditingHandlerFactory must not be {@literal null}. - */ - public AuditingEventListener(ObjectFactory auditingHandlerFactory) { - - Assert.notNull(auditingHandlerFactory, "IsNewAwareAuditingHandler must not be null!"); - this.auditingHandlerFactory = auditingHandlerFactory; - } - - @Override - public void onApplicationEvent(BeforeConvertEvent event) { - event.mapSource(it -> auditingHandlerFactory.getObject().markAudited(it)); - } - - @Override - public int getOrder() { - return 100; - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java deleted file mode 100644 index b028ab42e..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2010-2021 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 - * - * https://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.mapreduce; - -import java.util.Optional; - -import org.bson.Document; -import org.springframework.data.mongodb.core.query.Collation; -import org.springframework.lang.Nullable; - -/** - * Collects the parameters required to perform a group operation on a collection. The query condition and the input - * collection are specified on the group method as method arguments to be consistent with other operations, e.g. - * map-reduce. - * - * @author Mark Pollack - * @author Christoph Strobl - * @author Mark Paluch - * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0. - */ -@Deprecated -public class GroupBy { - - private @Nullable Document initialDocument; - private @Nullable String reduce; - - private Optional keys = Optional.empty(); - private Optional keyFunction = Optional.empty(); - private Optional initial = Optional.empty(); - private Optional finalize = Optional.empty(); - private Optional collation = Optional.empty(); - - public GroupBy(String... keys) { - - Document document = new Document(); - for (String key : keys) { - document.put(key, 1); - } - - this.keys = Optional.of(document); - } - - // NOTE GroupByCommand does not handle keyfunction. - - public GroupBy(@Nullable String key, boolean isKeyFunction) { - - Document document = new Document(); - if (isKeyFunction) { - keyFunction = Optional.ofNullable(key); - } else { - document.put(key, 1); - keys = Optional.of(document); - } - } - - /** - * Create new {@link GroupBy} with the field to group. - * - * @param key - * @return - */ - public static GroupBy keyFunction(String key) { - return new GroupBy(key, true); - } - - /** - * Create new {@link GroupBy} with the fields to group. - * - * @param keys - * @return - */ - public static GroupBy key(String... keys) { - return new GroupBy(keys); - } - - /** - * Define the aggregation result document. - * - * @param initialDocument can be {@literal null}. - * @return - */ - public GroupBy initialDocument(@Nullable String initialDocument) { - - initial = Optional.ofNullable(initialDocument); - return this; - } - - /** - * Define the aggregation result document. - * - * @param initialDocument can be {@literal null}. - * @return - */ - public GroupBy initialDocument(@Nullable Document initialDocument) { - - this.initialDocument = initialDocument; - return this; - } - - /** - * Define the aggregation function that operates on the documents during the grouping operation - * - * @param reduceFunction - * @return - */ - public GroupBy reduceFunction(String reduceFunction) { - - reduce = reduceFunction; - return this; - } - - /** - * Define the function that runs each item in the result set before db.collection.group() returns the final value. - * - * @param finalizeFunction - * @return - */ - public GroupBy finalizeFunction(@Nullable String finalizeFunction) { - - finalize = Optional.ofNullable(finalizeFunction); - return this; - } - - /** - * Define the Collation specifying language-specific rules for string comparison. - * - * @param collation can be {@literal null}. - * @return - * @since 2.0 - */ - public GroupBy collation(@Nullable Collation collation) { - - this.collation = Optional.ofNullable(collation); - return this; - } - - /** - * Get the {@link Document} representation of the {@link GroupBy}. - * - * @return - */ - public Document getGroupByObject() { - - Document document = new Document(); - - keys.ifPresent(val -> document.append("key", val)); - keyFunction.ifPresent(val -> document.append("$keyf", val)); - - document.put("$reduce", reduce); - document.put("initial", initialDocument); - - initial.ifPresent(val -> document.append("initial", val)); - finalize.ifPresent(val -> document.append("finalize", val)); - collation.ifPresent(val -> document.append("collation", val.toDocument())); - - return document; - } - -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupByResults.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupByResults.java deleted file mode 100644 index a93e67ee1..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupByResults.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2011-2021 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 - * - * https://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.mapreduce; - -import java.util.Iterator; -import java.util.List; - -import org.bson.Document; -import org.springframework.lang.Nullable; -import org.springframework.util.Assert; - -/** - * Collects the results of executing a group operation. - * - * @author Mark Pollack - * @author Christoph Strobl - * @author Mark Paluch - * @param The class in which the results are mapped onto, accessible via an {@link Iterator}. - * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0. - */ -@Deprecated -public class GroupByResults implements Iterable { - - private final List mappedResults; - private final Document rawResults; - - private double count; - private int keys; - private @Nullable String serverUsed; - - public GroupByResults(List mappedResults, Document rawResults) { - - Assert.notNull(mappedResults, "List of mapped results must not be null!"); - Assert.notNull(rawResults, "Raw results must not be null!"); - - this.mappedResults = mappedResults; - this.rawResults = rawResults; - - parseKeys(); - parseCount(); - parseServerUsed(); - } - - public double getCount() { - return count; - } - - public int getKeys() { - return keys; - } - - @Nullable - public String getServerUsed() { - return serverUsed; - } - - public Iterator iterator() { - return mappedResults.iterator(); - } - - public Document getRawResults() { - return rawResults; - } - - private void parseCount() { - - Object object = rawResults.get("count"); - if (object instanceof Number) { - count = ((Number) object).doubleValue(); - } - - } - - private void parseKeys() { - - Object object = rawResults.get("keys"); - if (object instanceof Number) { - keys = ((Number) object).intValue(); - } - } - - private void parseServerUsed() { - - // "serverUsed" : "127.0.0.1:27017" - Object object = rawResults.get("serverUsed"); - if (object instanceof String) { - serverUsed = (String) object; - } - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceCounts.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceCounts.java index ca28408c5..816709a58 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceCounts.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceCounts.java @@ -20,7 +20,9 @@ package org.springframework.data.mongodb.core.mapreduce; * * @author Mark Pollack * @author Oliver Gierke + * @deprecated since MongoDB server version 5.0 */ +@Deprecated public class MapReduceCounts { public static final MapReduceCounts NONE = new MapReduceCounts(-1, -1, -1); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java index 414d602a4..b26004e48 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java @@ -30,7 +30,9 @@ import com.mongodb.client.model.MapReduceAction; * @author Oliver Gierke * @author Christoph Strobl * @author Mark Paluch + * @deprecated since MongoDB server version 5.0 */ +@Deprecated public class MapReduceOptions { private @Nullable String outputCollection; @@ -95,19 +97,6 @@ public class MapReduceOptions { return this; } - /** - * With this option, no collection will be created, and the whole map-reduce operation will happen in RAM. Also, the - * results of the map-reduce will be returned within the result object. Note that this option is possible only when - * the result set fits within the 16MB limit of a single document. - * - * @return MapReduceOptions so that methods can be chained in a fluent API style - * @deprecated since 3.0 - Use {@link #actionInline()} instead. - */ - @Deprecated - public MapReduceOptions outputTypeInline() { - return actionInline(); - } - /** * With this option, no collection will be created, and the whole map-reduce operation will happen in RAM. Also, the * results of the map-reduce will be returned within the result object. Note that this option is possible only when @@ -122,17 +111,6 @@ public class MapReduceOptions { return this; } - /** - * This option will merge new data into the old output collection. In other words, if the same key exists in both the - * result set and the old collection, the new key will overwrite the old one. - * - * @return MapReduceOptions so that methods can be chained in a fluent API style - * @deprecated since 3.0 - use {@link #actionMerge()} instead. - */ - @Deprecated - public MapReduceOptions outputTypeMerge() { - return actionMerge(); - } /** * This option will merge new data into the old output collection. In other words, if the same key exists in both the @@ -147,19 +125,6 @@ public class MapReduceOptions { return this; } - /** - * If documents exists for a given key in the result set and in the old collection, then a reduce operation (using the - * specified reduce function) will be performed on the two values and the result will be written to the output - * collection. If a finalize function was provided, this will be run after the reduce as well. - * - * @return this. - * @deprecated since 3.0 - use {@link #actionReduce()} instead. - */ - @Deprecated - public MapReduceOptions outputTypeReduce() { - return actionReduce(); - } - /** * If documents exists for a given key in the result set and in the old collection, then a reduce operation (using the * specified reduce function) will be performed on the two values and the result will be written to the output @@ -174,18 +139,6 @@ public class MapReduceOptions { return this; } - /** - * The output will be inserted into a collection which will atomically replace any existing collection with the same - * name. Note, the default is {@link MapReduceAction#REPLACE}. - * - * @return MapReduceOptions so that methods can be chained in a fluent API style - * @deprecated since 3.0 - Use {@link #actionReplace()} instead. - */ - @Deprecated - public MapReduceOptions outputTypeReplace() { - return this.actionReplace(); - } - /** * The output will be inserted into a collection which will atomically replace any existing collection with the same * name. Note, the default is {@link MapReduceAction#REPLACE}. @@ -261,23 +214,6 @@ public class MapReduceOptions { return this; } - /** - * Add additional extra options that may not have a method on this class. This method will help if you use a version - * of this client library with a server version that has added additional map-reduce options that do not yet have an - * method for use in setting them. options - * - * @param key The key option - * @param value The value of the option - * @return MapReduceOptions so that methods can be chained in a fluent API style - * @deprecated since 1.7. - */ - @Deprecated - public MapReduceOptions extraOption(String key, Object value) { - - extraOptions.put(key, value); - return this; - } - /** * Define the Collation specifying language-specific rules for string comparison. * @@ -291,15 +227,6 @@ public class MapReduceOptions { return this; } - /** - * @return - * @deprecated since 1.7 - */ - @Deprecated - public Map getExtraOptions() { - return extraOptions; - } - public Optional getFinalizeFunction() { return this.finalizeFunction; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java index e1a49f35f..08523364d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java @@ -30,7 +30,9 @@ import org.springframework.util.Assert; * @author Christoph Strobl * @author Mark Paluch * @param The class in which the results are mapped onto, accessible via an iterator. + * @deprecated since MongoDB server version 5.0 */ +@Deprecated public class MapReduceResults implements Iterable { private final List mappedResults; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTiming.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTiming.java index caebef63a..116766014 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTiming.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTiming.java @@ -15,6 +15,11 @@ */ package org.springframework.data.mongodb.core.mapreduce; +/** + * @deprecated since MongoDB server version 5.0 + * + */ +@Deprecated public class MapReduceTiming { private long mapTime, emitLoopTime, totalTime; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/package-info.java index 54781e78c..65522d861 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/package-info.java @@ -1,6 +1,8 @@ /** * Support for MongoDB map-reduce operations. + * @deprecated since MongoDB server version 5.0 */ +@Deprecated @org.springframework.lang.NonNullApi package org.springframework.data.mongodb.core.mapreduce; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/messaging/ChangeStreamTask.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/messaging/ChangeStreamTask.java index e7c75c15c..beea250f3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/messaging/ChangeStreamTask.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/messaging/ChangeStreamTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -117,7 +117,7 @@ class ChangeStreamTask extends CursorReadingTask, } MongoDatabase db = StringUtils.hasText(options.getDatabaseName()) - ? template.getMongoDbFactory().getMongoDatabase(options.getDatabaseName()) + ? template.getMongoDatabaseFactory().getMongoDatabase(options.getDatabaseName()) : template.getDb(); ChangeStreamIterable iterable; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java index 1cb12fa0c..b55d6cc37 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -66,15 +66,6 @@ public class BasicUpdate extends Update { return this; } - @Override - @Deprecated - public Update pushAll(String key, Object[] values) { - Document keyValue = new Document(); - keyValue.put(key, values); - updateObject.put("$pushAll", keyValue); - return this; - } - @Override public Update addToSet(String key, @Nullable Object value) { updateObject.put("$addToSet", Collections.singletonMap(key, value)); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java index b856ba400..ff5ebacb4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java @@ -126,7 +126,7 @@ public class Collation { Assert.notNull(collation, "Collation must not be null!"); - return StringUtils.trimLeadingWhitespace(collation).startsWith("{") ? from(Document.parse(collation)) + return collation.stripLeading().startsWith("{") ? from(Document.parse(collation)) : of(collation); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java index de0fd584b..7bac32b1d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2022 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. @@ -87,18 +87,6 @@ public class Meta { setMaxTime(Duration.ofMillis(maxTimeMsec)); } - /** - * Set the maximum time limit for processing operations. - * - * @param timeout - * @param timeUnit - * @deprecated since 2.1. Use {@link #setMaxTime(Duration)} instead. - */ - @Deprecated - public void setMaxTime(long timeout, @Nullable TimeUnit timeUnit) { - setValue(MetaKey.MAX_TIME_MS.key, (timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS).toMillis(timeout)); - } - /** * Set the maximum time limit for processing operations. * @@ -290,14 +278,6 @@ public class Meta { */ EXHAUST, - /** - * Allows querying of a replica. - * - * @deprecated since 3.0.2, use {@link #SECONDARY_READS} instead. - */ - @Deprecated - SLAVE_OK, - /** * Allows querying of a replica. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java index 1984441f7..c46793ea5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -264,18 +264,6 @@ public final class NearQuery { return metric; } - /** - * Configures the maximum number of results to return. - * - * @param num - * @return - * @deprecated since 2.2. Please use {@link #limit(long)} instead. - */ - @Deprecated - public NearQuery num(long num) { - return limit(num); - } - /** * Configures the maximum number of results to return. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java index d4eab616f..67961be90 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -28,10 +28,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.concurrent.TimeUnit; import org.bson.Document; - import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; @@ -351,21 +349,6 @@ public class Query { return this; } - /** - * @param timeout - * @param timeUnit must not be {@literal null}. - * @return this. - * @see Meta#setMaxTime(long, TimeUnit) - * @since 1.6 - * @deprecated since 2.1. Use {@link #maxTime(Duration)} instead. - */ - @Deprecated - public Query maxTime(long timeout, TimeUnit timeUnit) { - - meta.setMaxTime(timeout, timeUnit); - return this; - } - /** * @param timeout must not be {@literal null}. * @return this. @@ -448,21 +431,6 @@ public class Query { return this; } - /** - * Allows querying of a replica. - * - * @return this. - * @see org.springframework.data.mongodb.core.query.Meta.CursorOption#SLAVE_OK - * @since 1.10 - * @deprecated since 3.0.2, use {@link #allowSecondaryReads()}. - */ - @Deprecated - public Query slaveOk() { - - meta.addFlag(Meta.CursorOption.SLAVE_OK); - return this; - } - /** * Allows querying of a replica. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java index 151c41b1e..8bc0aa9b8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -199,25 +199,6 @@ public class Update implements UpdateDefinition { return pushCommandBuilders.get(key); } - /** - * Update using the {@code $pushAll} update modifier.
      - * Note: In MongoDB 2.4 the usage of {@code $pushAll} has been deprecated in favor of {@code $push $each}. - * Important: As of MongoDB 3.6 {@code $pushAll} is not longer supported. Use {@code $push $each} instead. - * {@link #push(String)}) returns a builder that can be used to populate the {@code $each} object. - * - * @param key the field name. - * @param values must not be {@literal null}. - * @return this. - * @see MongoDB Update operator: - * $pushAll - * @deprecated as of MongoDB 2.4. Removed in MongoDB 3.6. Use {@link #push(String) $push $each} instead. - */ - @Deprecated - public Update pushAll(String key, Object[] values) { - addMultiFieldOperation("$pushAll", key, Arrays.asList(values)); - return this; - } - /** * Update using {@code $addToSet} modifier.
      * Allows creation of {@code $push} command for single or multiple (using {@code $each}) values @@ -457,23 +438,6 @@ public class Update implements UpdateDefinition { return !this.arrayFilters.isEmpty(); } - /** - * This method is not called anymore rather override {@link #addMultiFieldOperation(String, String, Object)}. - * - * @param operator - * @param key - * @param value - * @deprectaed Use {@link #addMultiFieldOperation(String, String, Object)} instead. - */ - @Deprecated - protected void addFieldOperation(String operator, String key, Object value) { - - Assert.hasText(key, "Key/Path for update must not be null or blank."); - - modifierOps.put(operator, new Document(key, value)); - this.keysToUpdate.add(key); - } - protected void addMultiFieldOperation(String operator, String key, @Nullable Object value) { Assert.hasText(key, "Key/Path for update must not be null or blank."); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/schema/TypedJsonSchemaObject.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/schema/TypedJsonSchemaObject.java index 3346ca6a4..2990f4059 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/schema/TypedJsonSchemaObject.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/schema/TypedJsonSchemaObject.java @@ -883,7 +883,7 @@ public class TypedJsonSchemaObject extends UntypedJsonSchemaObject { length.getUpperBound().getValue().ifPresent(it -> doc.append("maxLength", it)); } - if (!StringUtils.isEmpty(pattern)) { + if (StringUtils.hasText(pattern)) { doc.append("pattern", pattern); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java index 0e0145571..656f4fd1f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -123,11 +123,11 @@ public class MethodReferenceNode extends ExpressionNode { map.put("trim", mapArgRef().forOperator("$trim").mappingParametersTo("input", "chars")); map.put("ltrim", mapArgRef().forOperator("$ltrim").mappingParametersTo("input", "chars")); map.put("rtrim", mapArgRef().forOperator("$rtrim").mappingParametersTo("input", "chars")); - map.put("regexFind", mapArgRef().forOperator("$regexFind").mappingParametersTo("input", "regex" , "options")); - map.put("regexFindAll", mapArgRef().forOperator("$regexFindAll").mappingParametersTo("input", "regex" , "options")); - map.put("regexMatch", mapArgRef().forOperator("$regexMatch").mappingParametersTo("input", "regex" , "options")); - map.put("replaceOne", mapArgRef().forOperator("$replaceOne").mappingParametersTo("input", "find" , "replacement")); - map.put("replaceAll", mapArgRef().forOperator("$replaceAll").mappingParametersTo("input", "find" , "replacement")); + map.put("regexFind", mapArgRef().forOperator("$regexFind").mappingParametersTo("input", "regex", "options")); + map.put("regexFindAll", mapArgRef().forOperator("$regexFindAll").mappingParametersTo("input", "regex", "options")); + map.put("regexMatch", mapArgRef().forOperator("$regexMatch").mappingParametersTo("input", "regex", "options")); + map.put("replaceOne", mapArgRef().forOperator("$replaceOne").mappingParametersTo("input", "find", "replacement")); + map.put("replaceAll", mapArgRef().forOperator("$replaceAll").mappingParametersTo("input", "find", "replacement")); // TEXT SEARCH OPERATORS map.put("meta", singleArgRef().forOperator("$meta")); @@ -159,8 +159,10 @@ public class MethodReferenceNode extends ExpressionNode { map.put("literal", singleArgRef().forOperator("$literal")); // DATE OPERATORS - map.put("dateAdd", mapArgRef().forOperator("$dateAdd").mappingParametersTo("startDate", "unit", "amount", "timezone")); - map.put("dateDiff", mapArgRef().forOperator("$dateDiff").mappingParametersTo("startDate", "endDate", "unit","timezone", "startOfWeek")); + map.put("dateAdd", + mapArgRef().forOperator("$dateAdd").mappingParametersTo("startDate", "unit", "amount", "timezone")); + map.put("dateDiff", mapArgRef().forOperator("$dateDiff").mappingParametersTo("startDate", "endDate", "unit", + "timezone", "startOfWeek")); map.put("dayOfYear", singleArgRef().forOperator("$dayOfYear")); map.put("dayOfMonth", singleArgRef().forOperator("$dayOfMonth")); map.put("dayOfWeek", singleArgRef().forOperator("$dayOfWeek")); @@ -231,19 +233,6 @@ public class MethodReferenceNode extends ExpressionNode { super(reference, state); } - /** - * Returns the name of the method. - * - * @deprecated since 1.10. Please use {@link #getMethodReference()}. - */ - @Nullable - @Deprecated - public String getMethodName() { - - AggregationMethodReference methodReference = getMethodReference(); - return methodReference != null ? methodReference.getMongoOperator() : null; - } - /** * Return the {@link AggregationMethodReference}. * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/gridfs/GridFsResource.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/gridfs/GridFsResource.java index c6557bc7a..316eec596 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/gridfs/GridFsResource.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/gridfs/GridFsResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -170,7 +170,6 @@ public class GridFsResource extends InputStreamResource implements GridFsObject< * provided via {@link GridFSFile}. * @throws IllegalStateException if the file does not {@link #exists()}. */ - @SuppressWarnings("deprecation") public String getContentType() { Assert.state(exists(), () -> String.format("%s does not exist.", getDescription())); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/CollationUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/CollationUtils.java index 579b618a2..40f0527d5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/CollationUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/CollationUtils.java @@ -71,7 +71,7 @@ abstract class CollationUtils { return null; } - if (StringUtils.trimLeadingWhitespace(collationExpression).startsWith("{")) { + if (collationExpression.stripLeading().startsWith("{")) { ParameterBindingContext bindingContext = ParameterBindingContext.forExpressions(accessor::getBindableValue, expressionParser, dependencies -> evaluationContextProvider.getEvaluationContext(parameters, diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoParameterAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoParameterAccessor.java index 306ec6a3a..4b3a715e0 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoParameterAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoParameterAccessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -17,7 +17,6 @@ package org.springframework.data.mongodb.repository.query; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.publisher.MonoProcessor; import java.util.ArrayList; import java.util.List; @@ -35,7 +34,7 @@ import org.springframework.data.repository.util.ReactiveWrappers; */ class ReactiveMongoParameterAccessor extends MongoParametersParameterAccessor { - private final List> subscriptions; + private final List> subscriptions; public ReactiveMongoParameterAccessor(MongoQueryMethod method, Object[] values) { @@ -53,9 +52,9 @@ class ReactiveMongoParameterAccessor extends MongoParametersParameterAccessor { } if (ReactiveWrappers.isSingleValueType(value.getClass())) { - subscriptions.add(ReactiveWrapperConverters.toWrapper(value, Mono.class).toProcessor()); + subscriptions.add(ReactiveWrapperConverters.toWrapper(value, Mono.class).share()); } else { - subscriptions.add(ReactiveWrapperConverters.toWrapper(value, Flux.class).collectList().toProcessor()); + subscriptions.add(ReactiveWrapperConverters.toWrapper(value, Flux.class).collectList().share()); } } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAbstractMongodbQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAbstractMongodbQuery.java deleted file mode 100644 index 689bcdfcf..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAbstractMongodbQuery.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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.repository.support; - -import java.util.List; - -import org.bson.Document; -import org.bson.codecs.DocumentCodec; -import org.bson.json.JsonMode; -import org.bson.json.JsonWriterSettings; - -import org.springframework.lang.Nullable; - -import com.mongodb.MongoClientSettings; -import com.querydsl.core.DefaultQueryMetadata; -import com.querydsl.core.QueryModifiers; -import com.querydsl.core.SimpleQuery; -import com.querydsl.core.support.QueryMixin; -import com.querydsl.core.types.Expression; -import com.querydsl.core.types.FactoryExpression; -import com.querydsl.core.types.OrderSpecifier; -import com.querydsl.core.types.ParamExpression; -import com.querydsl.core.types.Predicate; -import com.querydsl.mongodb.document.AbstractMongodbQuery; -import com.querydsl.mongodb.document.MongodbDocumentSerializer; - -/** - * {@code QuerydslAbstractMongodbQuery} provides a base class for general Querydsl query implementation. - *

      - * Original implementation source {@link com.querydsl.mongodb.AbstractMongodbQuery} by {@literal The Querydsl Team} - * (http://www.querydsl.com/team) licensed under the Apache License, Version - * 2.0. - *

      - * Modified for usage with {@link MongodbDocumentSerializer}. - * - * @param concrete subtype - * @author laimw - * @author Mark Paluch - * @author Christoph Strobl - * @since 2.1 - * @deprecated since 3.3, use Querydsl's {@link AbstractMongodbQuery} directly. This class is deprecated for removal - * with the next major release. - */ -@Deprecated -public abstract class QuerydslAbstractMongodbQuery> - extends AbstractMongodbQuery - implements SimpleQuery { - - private static final JsonWriterSettings JSON_WRITER_SETTINGS = JsonWriterSettings.builder().outputMode(JsonMode.SHELL) - .build(); - - private final MongodbDocumentSerializer serializer; - private final QueryMixin queryMixin; - - /** - * Create a new MongodbQuery instance - * - * @param serializer serializer - */ - @SuppressWarnings("unchecked") - QuerydslAbstractMongodbQuery(MongodbDocumentSerializer serializer) { - - super(serializer); - - this.queryMixin = new QueryMixin<>((Q) this, new DefaultQueryMetadata(), false); - this.serializer = serializer; - } - - @Override - public Q distinct() { - return queryMixin.distinct(); - } - - @Override - public Q where(Predicate... e) { - return queryMixin.where(e); - } - - @Override - public Q limit(long limit) { - return queryMixin.limit(limit); - } - - @Override - public Q offset(long offset) { - return queryMixin.offset(offset); - } - - @Override - public Q restrict(QueryModifiers modifiers) { - return queryMixin.restrict(modifiers); - } - - @Override - public Q orderBy(OrderSpecifier... o) { - return queryMixin.orderBy(o); - } - - @Override - public Q set(ParamExpression param, T value) { - return queryMixin.set(param, value); - } - - /** - * Compute the actual projection {@link Document} from a given projectionExpression by serializing the contained - * {@link Expression expressions} individually. - * - * @param projectionExpression the computed projection {@link Document}. - * @return never {@literal null}. An empty {@link Document} by default. - * @see MongodbDocumentSerializer#handle(Expression) - */ - protected Document createProjection(@Nullable Expression projectionExpression) { - - if (!(projectionExpression instanceof FactoryExpression)) { - return new Document(); - } - - Document projection = new Document(); - ((FactoryExpression) projectionExpression).getArgs().stream() // - .filter(Expression.class::isInstance) // - .map(Expression.class::cast) // - .map(serializer::handle) // - .forEach(it -> projection.append(it.toString(), 1)); - - return projection; - } - - /** - * Compute the sort {@link Document} from the given list of {@link OrderSpecifier order specifiers}. - * - * @param orderSpecifiers can be {@literal null}. - * @return an empty {@link Document} if predicate is {@literal null}. - * @see MongodbDocumentSerializer#toSort(List) - */ - protected Document createSort(List> orderSpecifiers) { - return serializer.toSort(orderSpecifiers); - } - - /** - * Returns the {@literal Mongo Shell} representation of the query.
      - * The following query - * - *
      -	 *
      -	 * where(p.lastname.eq("Matthews")).orderBy(p.firstname.asc()).offset(1).limit(5);
      -	 * 
      - * - * results in - * - *
      -	 *
      -	 * find({"lastname" : "Matthews"}).sort({"firstname" : 1}).skip(1).limit(5)
      -	 * 
      - * - * Note that encoding to {@link String} may fail when using data types that cannot be encoded or DBRef's without an - * identifier. - * - * @return never {@literal null}. - */ - @Override - public String toString() { - - Document projection = createProjection(queryMixin.getMetadata().getProjection()); - Document sort = createSort(queryMixin.getMetadata().getOrderBy()); - DocumentCodec codec = new DocumentCodec(MongoClientSettings.getDefaultCodecRegistry()); - - StringBuilder sb = new StringBuilder("find(" + asDocument().toJson(JSON_WRITER_SETTINGS, codec)); - if (!projection.isEmpty()) { - sb.append(", ").append(projection.toJson(JSON_WRITER_SETTINGS, codec)); - } - sb.append(")"); - if (!sort.isEmpty()) { - sb.append(".sort(").append(sort.toJson(JSON_WRITER_SETTINGS, codec)).append(")"); - } - if (queryMixin.getMetadata().getModifiers().getOffset() != null) { - sb.append(".skip(").append(queryMixin.getMetadata().getModifiers().getOffset()).append(")"); - } - if (queryMixin.getMetadata().getModifiers().getLimit() != null) { - sb.append(".limit(").append(queryMixin.getMetadata().getModifiers().getLimit()).append(")"); - } - return sb.toString(); - } - - /** - * Obtain the {@literal Mongo Shell} json query representation. - * - * @return never {@literal null}. - * @since 2.2 - */ - public String toJson() { - return toJson(JSON_WRITER_SETTINGS); - } - - /** - * Obtain the json query representation applying given {@link JsonWriterSettings settings}. - * - * @param settings must not be {@literal null}. - * @return never {@literal null}. - * @since 2.2 - */ - public String toJson(JsonWriterSettings settings) { - return asDocument().toJson(settings); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAnyEmbeddedBuilder.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAnyEmbeddedBuilder.java deleted file mode 100644 index b6935a5e8..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslAnyEmbeddedBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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.repository.support; - -import java.util.Collection; - -import com.querydsl.core.support.QueryMixin; -import com.querydsl.core.types.ExpressionUtils; -import com.querydsl.core.types.Path; -import com.querydsl.core.types.Predicate; -import com.querydsl.mongodb.MongodbOps; - -/** - * {@code QuerydslAnyEmbeddedBuilder} is a builder for constraints on embedded objects. - *

      - * Original implementation source {@link com.querydsl.mongodb.AnyEmbeddedBuilder} by {@literal The Querydsl Team} - * (http://www.querydsl.com/team) licensed under the Apache License, Version - * 2.0. - *

      - * Modified for usage with {@link QuerydslAbstractMongodbQuery}. - * - * @param query type - * @author tiwe - * @author Mark Paluch - * @author Christoph Strobl - * @since 2.1 - * @deprecated since 3.3, use Querydsl's {@link com.querydsl.mongodb.document.AnyEmbeddedBuilder} directly. This class - * is deprecated for removal with the next major release. - */ -@Deprecated -public class QuerydslAnyEmbeddedBuilder, K> { - - private final QueryMixin queryMixin; - private final Path> collection; - - QuerydslAnyEmbeddedBuilder(QueryMixin queryMixin, Path> collection) { - - this.queryMixin = queryMixin; - this.collection = collection; - } - - /** - * Add the given where conditions. - * - * @param conditions must not be {@literal null}. - * @return the target {@link QueryMixin}. - * @see QueryMixin#where(Predicate) - */ - public Q on(Predicate... conditions) { - - return queryMixin - .where(ExpressionUtils.predicate(MongodbOps.ELEM_MATCH, collection, ExpressionUtils.allOf(conditions))); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslMongoRepository.java deleted file mode 100644 index 3cee8d5b8..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/QuerydslMongoRepository.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2011-2021 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 - * - * https://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.repository.support; - -import java.io.Serializable; - -import org.springframework.data.mongodb.core.MongoOperations; -import org.springframework.data.mongodb.repository.query.MongoEntityInformation; -import org.springframework.data.querydsl.EntityPathResolver; -import org.springframework.data.querydsl.QuerydslPredicateExecutor; - -import com.querydsl.core.types.Predicate; - -/** - * Special Querydsl based repository implementation that allows execution {@link Predicate}s in various forms. - * - * @author Oliver Gierke - * @author Thomas Darimont - * @author Mark Paluch - * @author Christoph Strobl - * @deprecated since 2.0. Querydsl execution is now linked via composable repositories and no longer requires to be a - * subclass of {@link SimpleMongoRepository}. Use {@link QuerydslMongoPredicateExecutor} for standalone - * Querydsl {@link Predicate} execution. - */ -@Deprecated -public class QuerydslMongoRepository extends QuerydslMongoPredicateExecutor - implements QuerydslPredicateExecutor { - - public QuerydslMongoRepository(MongoEntityInformation entityInformation, MongoOperations mongoOperations) { - super(entityInformation, mongoOperations); - } - - public QuerydslMongoRepository(MongoEntityInformation entityInformation, MongoOperations mongoOperations, - EntityPathResolver resolver) { - super(entityInformation, mongoOperations, resolver); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java index 296e98633..e5342673d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -102,8 +102,8 @@ public class ReactiveMongoRepositoryFactory extends ReactiveRepositoryFactorySup MongoEntityInformation entityInformation = getEntityInformation(metadata.getDomainType(), metadata); - fragments = fragments.append(RepositoryFragment.implemented(getTargetRepositoryViaReflection( - ReactiveQuerydslMongoPredicateExecutor.class, entityInformation, operations))); + fragments = fragments.append(RepositoryFragment + .implemented(instantiateClass(ReactiveQuerydslMongoPredicateExecutor.class, entityInformation, operations))); } return fragments; @@ -172,8 +172,7 @@ public class ReactiveMongoRepositoryFactory extends ReactiveRepositoryFactorySup return new ReactiveStringBasedMongoQuery(namedQuery, queryMethod, operations, expressionParser, evaluationContextProvider); } else if (queryMethod.hasAnnotatedAggregation()) { - return new ReactiveStringBasedAggregation(queryMethod, operations, expressionParser, - evaluationContextProvider); + return new ReactiveStringBasedAggregation(queryMethod, operations, expressionParser, evaluationContextProvider); } else if (queryMethod.hasAnnotatedQuery()) { return new ReactiveStringBasedMongoQuery(queryMethod, operations, expressionParser, evaluationContextProvider); } else { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java index c540a1460..7b8a5fe60 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java @@ -376,7 +376,7 @@ public class BsonUtils { */ public static Document toDocumentOrElse(String source, Function orElse) { - if (StringUtils.trimLeadingWhitespace(source).startsWith("{")) { + if (source.stripLeading().startsWith("{")) { return Document.parse(source); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoClientVersion.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoClientVersion.java index a7077e9a3..21e2fda32 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoClientVersion.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoClientVersion.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 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. @@ -36,33 +36,6 @@ public class MongoClientVersion { private static final boolean REACTIVE_CLIENT_PRESENT = ClassUtils .isPresent("com.mongodb.reactivestreams.client.MongoClient", MongoClientVersion.class.getClassLoader()); - /** - * @return {@literal true} if MongoDB Java driver version 3.0 or later is on classpath. - * @deprecated since 2.1, which requires MongoDB Java driver 3.8. Returns {@literal true} by default. - */ - @Deprecated - public static boolean isMongo3Driver() { - return true; - } - - /** - * @return {@literal true} if MongoDB Java driver version 3.4 or later is on classpath. - * @since 1.10 - * @deprecated since 2.1, which requires MongoDB Java driver 3.8. Returns {@literal true} by default. - */ - @Deprecated - public static boolean isMongo34Driver() { - return true; - } - - /** - * @return {@literal true} if MongoDB Java driver version 3.8 or later is on classpath. - * @since 2.1 - */ - public static boolean isMongo38Driver() { - return true; - } - /** * @return {@literal true} if the async MongoDB Java driver is on classpath. */ diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensions.kt index fdccda315..196957549 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,19 +15,6 @@ */ package org.springframework.data.mongodb.core -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableAggregationOperation.aggregateAndReturn] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("aggregateAndReturn()")) -fun ExecutableAggregationOperation.aggregateAndReturn(entityClass: KClass): ExecutableAggregationOperation.ExecutableAggregation = - aggregateAndReturn(entityClass.java) - /** * Extension for [ExecutableAggregationOperation.aggregateAndReturn] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensions.kt index 414ab0d4c..b6acf5dd8 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,22 +15,10 @@ */ package org.springframework.data.mongodb.core -import org.springframework.data.mongodb.core.query.asString -import kotlin.reflect.KClass +import org.springframework.data.mapping.toDotPath import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 -/** - * Extension for [ExecutableFindOperation.query] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("query()")) -fun ExecutableFindOperation.query(entityClass: KClass): ExecutableFindOperation.ExecutableFind = - query(entityClass.java) - /** * Extension for [ExecutableFindOperation.query] leveraging reified type parameters. * @@ -50,17 +38,6 @@ inline fun ExecutableFindOperation.query(): ExecutableFindOper inline fun ExecutableFindOperation.distinct(field : KProperty1): ExecutableFindOperation.TerminatingDistinct = query(T::class.java).distinct(field.name) -/** - * Extension for [ExecutableFindOperation.FindWithProjection.as] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ExecutableFindOperation.FindWithProjection<*>.asType(resultType: KClass): ExecutableFindOperation.FindWithQuery = - `as`(resultType.java) - /** * Extension for [ExecutableFindOperation.FindWithProjection.as] leveraging reified type parameters. * @@ -71,16 +48,6 @@ fun ExecutableFindOperation.FindWithProjection<*>.asType(resultType: K inline fun ExecutableFindOperation.FindWithProjection<*>.asType(): ExecutableFindOperation.FindWithQuery = `as`(T::class.java) -/** - * Extension for [ExecutableFindOperation.DistinctWithProjection.as] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ExecutableFindOperation.DistinctWithProjection.asType(resultType: KClass): ExecutableFindOperation.TerminatingDistinct = - `as`(resultType.java); - /** * Extension for [ExecutableFindOperation.DistinctWithProjection.as] leveraging reified type parameters. * @@ -98,4 +65,4 @@ inline fun ExecutableFindOperation.DistinctWithProjection.asTy * @since 3.0 */ fun ExecutableFindOperation.FindDistinct.distinct(key: KProperty<*>): ExecutableFindOperation.TerminatingDistinct = - distinct(asString(key)) + distinct(key.toDotPath()) diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensions.kt index aff46c4e1..c85e130f9 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,19 +15,6 @@ */ package org.springframework.data.mongodb.core -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableInsertOperation.insert] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("insert()")) -fun ExecutableInsertOperation.insert(entityClass: KClass): ExecutableInsertOperation.ExecutableInsert = - insert(entityClass.java) - /** * Extension for [ExecutableInsertOperation.insert] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensions.kt index 6d4fbb80d..36076f942 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -15,18 +15,6 @@ */ package org.springframework.data.mongodb.core -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableMapReduceOperation.mapReduce] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("mapReduce()")) -fun ExecutableMapReduceOperation.mapReduce(entityClass: KClass): ExecutableMapReduceOperation.MapReduceWithMapFunction = - mapReduce(entityClass.java) - /** * Extension for [ExecutableMapReduceOperation.mapReduce] leveraging reified type parameters. * @@ -36,16 +24,6 @@ fun ExecutableMapReduceOperation.mapReduce(entityClass: KClass): Ex inline fun ExecutableMapReduceOperation.mapReduce(): ExecutableMapReduceOperation.MapReduceWithMapFunction = mapReduce(T::class.java) -/** - * Extension for [ExecutableMapReduceOperation.MapReduceWithProjection.as] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ExecutableMapReduceOperation.MapReduceWithProjection<*>.asType(resultType: KClass): ExecutableMapReduceOperation.MapReduceWithQuery = - `as`(resultType.java) - /** * Extension for [ExecutableMapReduceOperation.MapReduceWithProjection.as] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensions.kt index ebe0e4c79..b2f39d3ad 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,19 +15,6 @@ */ package org.springframework.data.mongodb.core -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableRemoveOperation.remove] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("remove()")) -fun ExecutableRemoveOperation.remove(entityClass: KClass): ExecutableRemoveOperation.ExecutableRemove = - remove(entityClass.java) - /** * Extension for [ExecutableRemoveOperation.remove] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensions.kt index 8e114f192..d334ed696 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,18 +15,6 @@ */ package org.springframework.data.mongodb.core -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableUpdateOperation.update] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("update()")) -fun ExecutableUpdateOperation.update(entityClass: KClass): ExecutableUpdateOperation.ExecutableUpdate = - update(entityClass.java) - /** * Extension for [ExecutableUpdateOperation.update] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensions.kt index 602558df6..6d31afb81 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -26,22 +26,10 @@ import org.springframework.data.mongodb.core.aggregation.AggregationResults import org.springframework.data.mongodb.core.index.IndexOperations import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions import org.springframework.data.mongodb.core.mapreduce.MapReduceResults -import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.NearQuery import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update import java.util.stream.Stream -import kotlin.reflect.KClass - -/** - * Extension for [MongoOperations.getCollectionName] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("getCollectionName()")) -fun MongoOperations.getCollectionName(entityClass: KClass): String = - getCollectionName(entityClass.java) /** * Extension for [MongoOperations.getCollectionName] leveraging reified type parameters. @@ -83,17 +71,6 @@ inline fun MongoOperations.stream( if (collectionName != null) stream(query, T::class.java, collectionName) else stream(query, T::class.java) -/** - * Extension for [MongoOperations.createCollection] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("createCollection(collectionOptions)")) -fun MongoOperations.createCollection(entityClass: KClass, collectionOptions: CollectionOptions? = null): MongoCollection = - if (collectionOptions != null) createCollection(entityClass.java, collectionOptions) - else createCollection(entityClass.java) - /** * Extension for [MongoOperations.createCollection] leveraging reified type parameters. * @@ -105,16 +82,6 @@ inline fun MongoOperations.createCollection( if (collectionOptions != null) createCollection(T::class.java, collectionOptions) else createCollection(T::class.java) -/** - * Extension for [MongoOperations.collectionExists] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("collectionExists()")) -fun MongoOperations.collectionExists(entityClass: KClass): Boolean = - collectionExists(entityClass.java) - /** * Extension for [MongoOperations.collectionExists] leveraging reified type parameters. * @@ -124,17 +91,6 @@ fun MongoOperations.collectionExists(entityClass: KClass): Boolean inline fun MongoOperations.collectionExists(): Boolean = collectionExists(T::class.java) -/** - * Extension for [MongoOperations.dropCollection] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("dropCollection()")) -fun MongoOperations.dropCollection(entityClass: KClass) { - dropCollection(entityClass.java) -} - /** * Extension for [MongoOperations.dropCollection] leveraging reified type parameters. * @@ -145,16 +101,6 @@ inline fun MongoOperations.dropCollection() { dropCollection(T::class.java) } -/** - * Extension for [MongoOperations.indexOps] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("indexOps()")) -fun MongoOperations.indexOps(entityClass: KClass): IndexOperations = - indexOps(entityClass.java) - /** * Extension for [MongoOperations.indexOps] leveraging reified type parameters. * @@ -164,17 +110,6 @@ fun MongoOperations.indexOps(entityClass: KClass): IndexOperations inline fun MongoOperations.indexOps(): IndexOperations = indexOps(T::class.java) -/** - * Extension for [MongoOperations.bulkOps] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("bulkOps(bulkMode, collectionName)")) -fun MongoOperations.bulkOps(bulkMode: BulkMode, entityClass: KClass, collectionName: String? = null): BulkOperations = - if (collectionName != null) bulkOps(bulkMode, entityClass.java, collectionName) - else bulkOps(bulkMode, entityClass.java) - /** * Extension for [MongoOperations.bulkOps] leveraging reified type parameters. * @@ -195,44 +130,6 @@ inline fun MongoOperations.bulkOps(bulkMode: BulkMode, collect inline fun MongoOperations.findAll(collectionName: String? = null): List = if (collectionName != null) findAll(T::class.java, collectionName) else findAll(T::class.java) -/** - * Extension for [MongoOperations.group] leveraging reified type parameters. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Suppress("DEPRECATION") -@Deprecated("since 2.2, the `group` command has been removed in MongoDB Server 4.2.0.", replaceWith = ReplaceWith("aggregate()")) -inline fun MongoOperations.group(inputCollectionName: String, groupBy: org.springframework.data.mongodb.core.mapreduce.GroupBy): org.springframework.data.mongodb.core.mapreduce.GroupByResults = - group(inputCollectionName, groupBy, T::class.java) - -/** - * Extension for [MongoOperations.group] leveraging reified type parameters. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Suppress("DEPRECATION") -@Deprecated("since 2.2, the `group` command has been removed in MongoDB Server 4.2.0.", replaceWith = ReplaceWith("aggregate()")) -inline fun MongoOperations.group(criteria: Criteria, inputCollectionName: String, groupBy: org.springframework.data.mongodb.core.mapreduce.GroupBy): org.springframework.data.mongodb.core.mapreduce.GroupByResults = - group(criteria, inputCollectionName, groupBy, T::class.java) - -/** - * Extension for [MongoOperations.aggregate] leveraging reified type parameters. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated( - "Since 2.2, use the reified variant", - replaceWith = ReplaceWith("aggregate(aggregation)") -) -inline fun MongoOperations.aggregate( - aggregation: Aggregation, - inputType: KClass<*> -): AggregationResults = - aggregate(aggregation, inputType.java, O::class.java) - /** * Extension for [MongoOperations.aggregate] leveraging reified type parameters. * @@ -254,22 +151,6 @@ inline fun MongoOperations.aggregate( ): AggregationResults = aggregate(aggregation, collectionName, O::class.java) -/** - * Extension for [MongoOperations.aggregateStream] leveraging reified type parameters. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated( - "Since 2.2, use the reified variant", - replaceWith = ReplaceWith("aggregateStream(aggregation)") -) -inline fun MongoOperations.aggregateStream( - aggregation: Aggregation, - inputType: KClass<*> -): Stream = - aggregateStream(aggregation, inputType.java, O::class.java) - /** * Extension for [MongoOperations.aggregateStream] leveraging reified type parameters. * @@ -332,17 +213,6 @@ inline fun MongoOperations.geoNear(near: NearQuery, collection inline fun MongoOperations.findOne(query: Query, collectionName: String? = null): T? = if (collectionName != null) findOne(query, T::class.java, collectionName) else findOne(query, T::class.java) -/** - * Extension for [MongoOperations.exists] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("exists(query, collectionName)")) -fun MongoOperations.exists(query: Query, entityClass: KClass, collectionName: String? = null): Boolean = - if (collectionName != null) exists(query, entityClass.java, collectionName) - else exists(query, entityClass.java) - /** * Extension for [MongoOperations.exists] leveraging reified type parameters. * @@ -374,36 +244,6 @@ inline fun MongoOperations.findById(id: Any, collectionName: S if (collectionName != null) findById(id, T::class.java, collectionName) else findById(id, T::class.java) -/** - * Extension for [MongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(field)")) -inline fun MongoOperations.findDistinct(field: String, entityClass: KClass<*>): List = - findDistinct(field, entityClass.java, T::class.java) - -/** - * Extension for [MongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(query, field)")) -inline fun MongoOperations.findDistinct(query: Query, field: String, entityClass: KClass<*>): List = - findDistinct(query, field, entityClass.java, T::class.java) - -/** - * Extension for [MongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(query, field, collectionName)")) -inline fun MongoOperations.findDistinct(query: Query, field: String, collectionName: String, entityClass: KClass<*>): List = - findDistinct(query, field, collectionName, entityClass.java, T::class.java) - /** * Extension for [MongoOperations.findDistinct] leveraging reified type parameters. * @@ -435,17 +275,6 @@ inline fun MongoOperations.findAndRemove(query: Query, collect if (collectionName != null) findAndRemove(query, T::class.java, collectionName) else findAndRemove(query, T::class.java) -/** - * Extension for [MongoOperations.count] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("count(query, collectionName)")) -fun MongoOperations.count(query: Query = Query(), entityClass: KClass, collectionName: String? = null): Long = - if (collectionName != null) count(query, entityClass.java, collectionName) - else count(query, entityClass.java) - /** * Extension for [MongoOperations.count] leveraging reified type parameters. * @@ -456,17 +285,6 @@ fun MongoOperations.count(query: Query = Query(), entityClass: KClass< inline fun MongoOperations.count(query: Query = Query(), collectionName: String? = null): Long = if (collectionName != null) count(query, T::class.java, collectionName) else count(query, T::class.java) -/** - * Extension for [MongoOperations.insert] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("insert(batchToSave)")) -fun MongoOperations.insert(batchToSave: Collection, entityClass: KClass) { - insert(batchToSave, entityClass.java) -} - /** * Extension for [MongoOperations.insert] leveraging reified type parameters. * @@ -476,17 +294,6 @@ fun MongoOperations.insert(batchToSave: Collection, entityClass: KC @Suppress("EXTENSION_SHADOWED_BY_MEMBER") inline fun MongoOperations.insert(batchToSave: Collection): Collection = insert(batchToSave, T::class.java) -/** - * Extension for [MongoOperations.upsert] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("upsert(query, update, collectionName)")) -fun MongoOperations.upsert(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): UpdateResult = - if (collectionName != null) upsert(query, update, entityClass.java, collectionName) - else upsert(query, update, entityClass.java) - /** * Extension for [MongoOperations.upsert] leveraging reified type parameters. * @@ -498,17 +305,6 @@ inline fun MongoOperations.upsert(query: Query, update: Update if (collectionName != null) upsert(query, update, T::class.java, collectionName) else upsert(query, update, T::class.java) -/** - * Extension for [MongoOperations.updateFirst] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("updateFirst(query, update, collectionName)")) -fun MongoOperations.updateFirst(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): UpdateResult = - if (collectionName != null) updateFirst(query, update, entityClass.java, collectionName) - else updateFirst(query, update, entityClass.java) - /** * Extension for [MongoOperations.updateFirst] leveraging reified type parameters. * @@ -520,17 +316,6 @@ inline fun MongoOperations.updateFirst(query: Query, update: U if (collectionName != null) updateFirst(query, update, T::class.java, collectionName) else updateFirst(query, update, T::class.java) -/** - * Extension for [MongoOperations.updateMulti] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("updateMulti(query, update, collectionName)")) -fun MongoOperations.updateMulti(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): UpdateResult = - if (collectionName != null) updateMulti(query, update, entityClass.java, collectionName) - else updateMulti(query, update, entityClass.java) - /** * Extension for [MongoOperations.updateMulti] leveraging reified type parameters. * @@ -542,17 +327,6 @@ inline fun MongoOperations.updateMulti(query: Query, update: U if (collectionName != null) updateMulti(query, update, T::class.java, collectionName) else updateMulti(query, update, T::class.java) -/** - * Extension for [MongoOperations.remove] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("remove(query, collectionName)")) -fun MongoOperations.remove(query: Query, entityClass: KClass, collectionName: String? = null): DeleteResult = - if (collectionName != null) remove(query, entityClass.java, collectionName) - else remove(query, entityClass.java) - /** * Extension for [MongoOperations.remove] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensions.kt index 89982f9bd..d75c82b58 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -17,17 +17,6 @@ package org.springframework.data.mongodb.core import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow -import kotlin.reflect.KClass - -/** - * Extension for [ExecutableAggregationOperation.aggregateAndReturn] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("aggregateAndReturn()")) -fun ReactiveAggregationOperation.aggregateAndReturn(entityClass: KClass): ReactiveAggregationOperation.ReactiveAggregation = - aggregateAndReturn(entityClass.java) /** * Extension for [ExecutableAggregationOperation.aggregateAndReturn] leveraging reified type parameters. diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensions.kt index bbc4f36a6..af1f09c8b 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,21 +20,10 @@ import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitSingle import org.springframework.data.geo.GeoResult -import org.springframework.data.mongodb.core.query.asString -import kotlin.reflect.KClass +import org.springframework.data.mapping.toDotPath import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 -/** - * Extension for [ReactiveFindOperation.query] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("query()")) -fun ReactiveFindOperation.query(entityClass: KClass): ReactiveFindOperation.ReactiveFind = - query(entityClass.java) - /** * Extension for [ReactiveFindOperation.query] leveraging reified type parameters. * @@ -53,16 +42,6 @@ inline fun ReactiveFindOperation.query(): ReactiveFindOperatio inline fun ReactiveFindOperation.distinct(field : KProperty1): ReactiveFindOperation.TerminatingDistinct = query(T::class.java).distinct(field.name) -/** - * Extension for [ReactiveFindOperation.FindWithProjection.as] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ReactiveFindOperation.FindWithProjection<*>.asType(resultType: KClass): ReactiveFindOperation.FindWithQuery = - `as`(resultType.java) - /** * Extension for [ReactiveFindOperation.FindWithProjection.as] leveraging reified type parameters. * @@ -72,16 +51,6 @@ fun ReactiveFindOperation.FindWithProjection<*>.asType(resultType: KCl inline fun ReactiveFindOperation.FindWithProjection<*>.asType(): ReactiveFindOperation.FindWithQuery = `as`(T::class.java) -/** - * Extension for [ExecutableFindOperation.DistinctWithProjection.as] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ReactiveFindOperation.DistinctWithProjection.asType(resultType: KClass): ReactiveFindOperation.TerminatingDistinct = - `as`(resultType.java); - /** * Extension for [ReactiveFindOperation.DistinctWithProjection.as] leveraging reified type parameters. * @@ -98,7 +67,7 @@ inline fun ReactiveFindOperation.DistinctWithProjection.asType * @since 3.0 */ fun ReactiveFindOperation.FindDistinct.distinct(key: KProperty<*>): ReactiveFindOperation.TerminatingDistinct = - distinct(asString(key)) + distinct(key.toDotPath()) /** * Non-nullable Coroutines variant of [ReactiveFindOperation.TerminatingFind.one]. diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensions.kt index ca9147e2b..c650cd12f 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -18,17 +18,6 @@ package org.springframework.data.mongodb.core import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitSingle -import kotlin.reflect.KClass - -/** - * Extension for [ReactiveInsertOperation.insert] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("insert()")) -fun ReactiveInsertOperation.insert(entityClass: KClass): ReactiveInsertOperation.ReactiveInsert = - insert(entityClass.java) /** * Extension for [ReactiveInsertOperation.insert] leveraging reified type parameters. diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensions.kt index e9b27cde1..e271b644f 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -17,17 +17,6 @@ package org.springframework.data.mongodb.core import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow -import kotlin.reflect.KClass - -/** - * Extension for [ReactiveMapReduceOperation.mapReduce] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("mapReduce()")) -fun ReactiveMapReduceOperation.mapReduce(entityClass: KClass): ReactiveMapReduceOperation.MapReduceWithMapFunction = - mapReduce(entityClass.java) /** * Extension for [ReactiveMapReduceOperation.mapReduce] leveraging reified type parameters. @@ -38,16 +27,6 @@ fun ReactiveMapReduceOperation.mapReduce(entityClass: KClass): Reac inline fun ReactiveMapReduceOperation.mapReduce(): ReactiveMapReduceOperation.MapReduceWithMapFunction = mapReduce(T::class.java) -/** - * Extension for [ReactiveMapReduceOperation.MapReduceWithProjection.as] providing a [KClass] based variant. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("asType()")) -fun ReactiveMapReduceOperation.MapReduceWithProjection<*>.asType(resultType: KClass): ReactiveMapReduceOperation.MapReduceWithQuery = - `as`(resultType.java) - /** * Extension for [ReactiveMapReduceOperation.MapReduceWithProjection.as] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensions.kt index 670c69164..669df142b 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -28,17 +28,6 @@ import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update import reactor.core.publisher.Flux import reactor.core.publisher.Mono -import kotlin.reflect.KClass - -/** - * Extension for [ReactiveMongoOperations.indexOps] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("indexOps()")) -fun ReactiveMongoOperations.indexOps(entityClass: KClass): ReactiveIndexOperations = - indexOps(entityClass.java) /** * Extension for [ReactiveMongoOperations.indexOps] leveraging reified type parameters. @@ -58,16 +47,6 @@ inline fun ReactiveMongoOperations.indexOps(): ReactiveIndexOp inline fun ReactiveMongoOperations.execute(action: ReactiveCollectionCallback): Flux = execute(T::class.java, action) -/** - * Extension for [ReactiveMongoOperations.createCollection] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("createCollection(collectionOptions)")) -fun ReactiveMongoOperations.createCollection(entityClass: KClass, collectionOptions: CollectionOptions? = null): Mono> = - if (collectionOptions != null) createCollection(entityClass.java, collectionOptions) else createCollection(entityClass.java) - /** * Extension for [ReactiveMongoOperations.createCollection] leveraging reified type parameters. * @@ -77,16 +56,6 @@ fun ReactiveMongoOperations.createCollection(entityClass: KClass, c inline fun ReactiveMongoOperations.createCollection(collectionOptions: CollectionOptions? = null): Mono> = if (collectionOptions != null) createCollection(T::class.java, collectionOptions) else createCollection(T::class.java) -/** - * Extension for [ReactiveMongoOperations.collectionExists] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("collectionExists()")) -fun ReactiveMongoOperations.collectionExists(entityClass: KClass): Mono = - collectionExists(entityClass.java) - /** * Extension for [ReactiveMongoOperations.collectionExists] leveraging reified type parameters. * @@ -96,16 +65,6 @@ fun ReactiveMongoOperations.collectionExists(entityClass: KClass): inline fun ReactiveMongoOperations.collectionExists(): Mono = collectionExists(T::class.java) -/** - * Extension for [ReactiveMongoOperations.dropCollection] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("dropCollection()")) -fun ReactiveMongoOperations.dropCollection(entityClass: KClass): Mono = - dropCollection(entityClass.java) - /** * Extension for [ReactiveMongoOperations.dropCollection] leveraging reified type parameters. * @@ -133,16 +92,6 @@ inline fun ReactiveMongoOperations.findAll(collectionName: Str inline fun ReactiveMongoOperations.findOne(query: Query, collectionName: String? = null): Mono = if (collectionName != null) findOne(query, T::class.java, collectionName) else findOne(query, T::class.java) -/** - * Extension for [ReactiveMongoOperations.exists] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("exists(query, collectionName)")) -fun ReactiveMongoOperations.exists(query: Query, entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) exists(query, entityClass.java, collectionName) else exists(query, entityClass.java) - /** * Extension for [ReactiveMongoOperations.exists] leveraging reified type parameters. * @@ -171,36 +120,6 @@ inline fun ReactiveMongoOperations.find(query: Query, collecti inline fun ReactiveMongoOperations.findById(id: Any, collectionName: String? = null): Mono = if (collectionName != null) findById(id, T::class.java, collectionName) else findById(id, T::class.java) -/** - * Extension for [ReactiveMongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(field)")) -inline fun ReactiveMongoOperations.findDistinct(field: String, entityClass: KClass<*>): Flux = - findDistinct(field, entityClass.java, T::class.java); - -/** - * Extension for [ReactiveMongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(query, field)")) -inline fun ReactiveMongoOperations.findDistinct(query: Query, field: String, entityClass: KClass<*>): Flux = - findDistinct(query, field, entityClass.java, T::class.java) - -/** - * Extension for [ReactiveMongoOperations.findDistinct] leveraging reified type parameters. - * - * @author Christoph Strobl - * @since 2.1 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("findDistinct(query, field, collectionName)")) -inline fun ReactiveMongoOperations.findDistinct(query: Query, field: String, collectionName: String, entityClass: KClass<*>): Flux = - findDistinct(query, field, collectionName, entityClass.java, T::class.java) - /** * Extension for [ReactiveMongoOperations.findDistinct] leveraging reified type parameters. * @@ -288,17 +207,6 @@ inline fun ReactiveMongoOperations.findAndRemove(query: Query, if (collectionName != null) findAndRemove(query, T::class.java, collectionName) else findAndRemove(query, T::class.java) -/** - * Extension for [ReactiveMongoOperations.count] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("count(query, collectionName)")) -fun ReactiveMongoOperations.count(query: Query = Query(), entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) count(query, entityClass.java, collectionName) - else count(query, entityClass.java) - /** * Extension for [ReactiveMongoOperations.count] leveraging reified type parameters. * @@ -310,16 +218,6 @@ inline fun ReactiveMongoOperations.count(query: Query = Query( if (collectionName != null) count(query, T::class.java, collectionName) else count(query, T::class.java) -/** - * Extension for [ReactiveMongoOperations.insert] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("insert(batchToSave)")) -fun ReactiveMongoOperations.insert(batchToSave: Collection, entityClass: KClass): Flux = - insert(batchToSave, entityClass.java) - /** * Extension for [ReactiveMongoOperations.insert] leveraging reified type parameters. * @@ -329,26 +227,6 @@ fun ReactiveMongoOperations.insert(batchToSave: Collection, entityC @Suppress("EXTENSION_SHADOWED_BY_MEMBER") inline fun ReactiveMongoOperations.insert(batchToSave: Collection): Flux = insert(batchToSave, T::class.java) -/** - * Extension for [ReactiveMongoOperations.insertAll] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("insertAll(batchToSave)")) -fun ReactiveMongoOperations.insertAll(batchToSave: Mono>, entityClass: KClass): Flux = - insertAll(batchToSave, entityClass.java) - -/** - * Extension for [ReactiveMongoOperations.upsert] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("upsert(query, update, collectionName)")) -fun ReactiveMongoOperations.upsert(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) upsert(query, update, entityClass.java, collectionName) else upsert(query, update, entityClass.java) - /** * Extension for [ReactiveMongoOperations.upsert] leveraging reified type parameters. * @@ -360,17 +238,6 @@ inline fun ReactiveMongoOperations.upsert(query: Query, update if (collectionName != null) upsert(query, update, T::class.java, collectionName) else upsert(query, update, T::class.java) -/** - * Extension for [ReactiveMongoOperations.updateFirst] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("updateFirst(query, update, collectionName)")) -fun ReactiveMongoOperations.updateFirst(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) updateFirst(query, update, entityClass.java, collectionName) - else updateFirst(query, update, entityClass.java) - /** * Extension for [ReactiveMongoOperations.updateFirst] leveraging reified type parameters. * @@ -382,17 +249,6 @@ inline fun ReactiveMongoOperations.updateFirst(query: Query, u if (collectionName != null) updateFirst(query, update, T::class.java, collectionName) else updateFirst(query, update, T::class.java) -/** - * Extension for [ReactiveMongoOperations.updateMulti] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("updateMulti(query, update, collectionName)")) -fun ReactiveMongoOperations.updateMulti(query: Query, update: Update, entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) updateMulti(query, update, entityClass.java, collectionName) - else updateMulti(query, update, entityClass.java) - /** * Extension for [ReactiveMongoOperations.updateMulti] leveraging reified type parameters. * @@ -404,17 +260,6 @@ inline fun ReactiveMongoOperations.updateMulti(query: Query, u if (collectionName != null) updateMulti(query, update, T::class.java, collectionName) else updateMulti(query, update, T::class.java) -/** - * Extension for [ReactiveMongoOperations.remove] providing a [KClass] based variant. - * - * @author Sebastien Deleuze - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("remove(query, collectionName)")) -fun ReactiveMongoOperations.remove(query: Query, entityClass: KClass, collectionName: String? = null): Mono = - if (collectionName != null) remove(query, entityClass.java, collectionName) - else remove(query, entityClass.java) - /** * Extension for [ReactiveMongoOperations.remove] leveraging reified type parameters. * diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensions.kt index 1b46f7274..ac2268413 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,17 +19,6 @@ import com.mongodb.client.result.DeleteResult import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitSingle -import kotlin.reflect.KClass - -/** - * Extension for [ReactiveRemoveOperation.remove] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("remove()")) -fun ReactiveRemoveOperation.remove(entityClass: KClass): ReactiveRemoveOperation.ReactiveRemove = - remove(entityClass.java) /** * Extension for [ReactiveRemoveOperation.remove] leveraging reified type parameters. diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensions.kt index d15a3567f..a328f9286 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -18,17 +18,6 @@ package org.springframework.data.mongodb.core import com.mongodb.client.result.UpdateResult import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitSingle -import kotlin.reflect.KClass - -/** - * Extension for [ReactiveUpdateOperation.update] providing a [KClass] based variant. - * - * @author Mark Paluch - * @since 2.0 - */ -@Deprecated("Since 2.2, use the reified variant", replaceWith = ReplaceWith("update()")) -fun ReactiveUpdateOperation.update(entityClass: KClass): ReactiveUpdateOperation.ReactiveUpdate = - update(entityClass.java) /** * Extension for [ReactiveUpdateOperation.update] leveraging reified type parameters. diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensions.kt index 8d13ad7d3..fe885ee8c 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -15,6 +15,7 @@ */ package org.springframework.data.mongodb.core.query +import org.springframework.data.mapping.toDotPath import kotlin.reflect.KProperty /** @@ -47,7 +48,7 @@ fun Criteria.inValues(vararg o: Any?): Criteria = `in`(*o) * @author Tjeu Kayim * @since 2.2 */ -fun where(key: KProperty<*>): Criteria = Criteria.where(asString(key)) +fun where(key: KProperty<*>): Criteria = Criteria.where(key.toDotPath()) /** * Add new key to the criteria chain using a KProperty. @@ -55,4 +56,4 @@ fun where(key: KProperty<*>): Criteria = Criteria.where(asString(key)) * @author Tjeu Kayim * @since 2.2 */ -infix fun Criteria.and(key: KProperty<*>): Criteria = and(asString(key)) +infix fun Criteria.and(key: KProperty<*>): Criteria = and(key.toDotPath()) diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPath.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPath.kt deleted file mode 100644 index 01325069f..000000000 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPath.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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.query - -import org.springframework.data.mapping.toDotPath -import kotlin.reflect.KProperty -import kotlin.reflect.KProperty1 - -/** - * Abstraction of a property path consisting of [KProperty]. - * - * @author Tjeu Kayim - * @author Mark Paluch - * @author Yoann de Martino - * @since 2.2 - * @deprecated since 3.2, KPropertyPath from Spring Data Commons. - */ -@Deprecated("use KPropertyPath from Spring Data Commons", replaceWith = ReplaceWith("KPropertyPath", "org.springframework.data.mapping.KPropertyPath")) -class KPropertyPath( - internal val parent: KProperty, - internal val child: KProperty1 -) : KProperty by child - -/** - * Recursively construct field name for a nested property. - * @author Tjeu Kayim - */ -internal fun asString(property: KProperty<*>): String { - return when (property) { - is KPropertyPath<*, *> -> - "${asString(property.parent)}.${property.child.name}" - else -> property.toDotPath() - } -} - -/** - * Builds [KPropertyPath] from Property References. - * Refer to a field in an embedded/nested document. - * - * For example, referring to the field "author.name": - * ``` - * Book::author / Author::name isEqualTo "Herman Melville" - * ``` - * @author Tjeu Kayim - * @author Yoann de Martino - * @since 2.2 - * @deprecated since 3.2, KPropertyPath.div from Spring Data Commons. - */ -@Deprecated("use KPropertyPath.div from Spring Data Commons", replaceWith = ReplaceWith("this / other", "org.springframework.data.mapping.div")) -operator fun KProperty.div(other: KProperty1) = - KPropertyPath(this, other) diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathExtensions.kt deleted file mode 100644 index 411d3697e..000000000 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathExtensions.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2020-2021 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 - * - * https://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.query - -import kotlin.reflect.KProperty - -/** - * Extension for [KProperty] providing an `toPath` function to render a [KProperty] as property path. - * - * @author Mark Paluch - * @since 3.1 - */ -fun KProperty<*>.toPath(): String = asString(this) diff --git a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensions.kt b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensions.kt index ab7e32fc0..9f7583047 100644 --- a/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensions.kt +++ b/spring-data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensions.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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,7 @@ import org.bson.BsonRegularExpression import org.springframework.data.geo.Circle import org.springframework.data.geo.Point import org.springframework.data.geo.Shape +import org.springframework.data.mapping.toDotPath import org.springframework.data.mongodb.core.geo.GeoJson import org.springframework.data.mongodb.core.schema.JsonSchemaObject import java.util.regex.Pattern @@ -31,7 +32,7 @@ import kotlin.reflect.KProperty * @see Criteria.isEqualTo */ infix fun KProperty.isEqualTo(value: T) = - Criteria(asString(this)).isEqualTo(value) + Criteria(this.toDotPath()).isEqualTo(value) /** * Creates a criterion using the $ne operator. @@ -42,7 +43,7 @@ infix fun KProperty.isEqualTo(value: T) = * @see Criteria.ne */ infix fun KProperty.ne(value: T): Criteria = - Criteria(asString(this)).ne(value) + Criteria(this.toDotPath()).ne(value) /** * Creates a criterion using the $lt operator. @@ -53,7 +54,7 @@ infix fun KProperty.ne(value: T): Criteria = * @see Criteria.lt */ infix fun KProperty.lt(value: T): Criteria = - Criteria(asString(this)).lt(value) + Criteria(this.toDotPath()).lt(value) /** * Creates a criterion using the $lte operator. @@ -64,7 +65,7 @@ infix fun KProperty.lt(value: T): Criteria = * @see Criteria.lte */ infix fun KProperty.lte(value: T): Criteria = - Criteria(asString(this)).lte(value) + Criteria(this.toDotPath()).lte(value) /** * Creates a criterion using the $gt operator. @@ -75,7 +76,7 @@ infix fun KProperty.lte(value: T): Criteria = * @see Criteria.gt */ infix fun KProperty.gt(value: T): Criteria = - Criteria(asString(this)).gt(value) + Criteria(this.toDotPath()).gt(value) /** * Creates a criterion using the $gte operator. @@ -86,7 +87,7 @@ infix fun KProperty.gt(value: T): Criteria = * @see Criteria.gte */ infix fun KProperty.gte(value: T): Criteria = - Criteria(asString(this)).gte(value) + Criteria(this.toDotPath()).gte(value) /** * Creates a criterion using the $in operator. @@ -97,7 +98,7 @@ infix fun KProperty.gte(value: T): Criteria = * @see Criteria.inValues */ fun KProperty.inValues(vararg o: Any): Criteria = - Criteria(asString(this)).`in`(*o) + Criteria(this.toDotPath()).`in`(*o) /** * Creates a criterion using the $in operator. @@ -108,7 +109,7 @@ fun KProperty.inValues(vararg o: Any): Criteria = * @see Criteria.inValues */ infix fun KProperty.inValues(value: Collection): Criteria = - Criteria(asString(this)).`in`(value) + Criteria(this.toDotPath()).`in`(value) /** * Creates a criterion using the $nin operator. @@ -119,7 +120,7 @@ infix fun KProperty.inValues(value: Collection): Criteria = * @see Criteria.nin */ fun KProperty.nin(vararg o: Any): Criteria = - Criteria(asString(this)).nin(*o) + Criteria(this.toDotPath()).nin(*o) /** * Creates a criterion using the $nin operator. @@ -130,7 +131,7 @@ fun KProperty.nin(vararg o: Any): Criteria = * @see Criteria.nin */ infix fun KProperty.nin(value: Collection): Criteria = - Criteria(asString(this)).nin(value) + Criteria(this.toDotPath()).nin(value) /** * Creates a criterion using the $mod operator. @@ -141,7 +142,7 @@ infix fun KProperty.nin(value: Collection): Criteria = * @see Criteria.mod */ fun KProperty.mod(value: Number, remainder: Number): Criteria = - Criteria(asString(this)).mod(value, remainder) + Criteria(this.toDotPath()).mod(value, remainder) /** * Creates a criterion using the $all operator. @@ -152,7 +153,7 @@ fun KProperty.mod(value: Number, remainder: Number): Criteria = * @see Criteria.all */ fun KProperty<*>.all(vararg o: Any): Criteria = - Criteria(asString(this)).all(*o) + Criteria(this.toDotPath()).all(*o) /** * Creates a criterion using the $all operator. @@ -163,7 +164,7 @@ fun KProperty<*>.all(vararg o: Any): Criteria = * @see Criteria.all */ infix fun KProperty<*>.all(value: Collection<*>): Criteria = - Criteria(asString(this)).all(value) + Criteria(this.toDotPath()).all(value) /** * Creates a criterion using the $size operator. @@ -174,7 +175,7 @@ infix fun KProperty<*>.all(value: Collection<*>): Criteria = * @see Criteria.size */ infix fun KProperty<*>.size(s: Int): Criteria = - Criteria(asString(this)).size(s) + Criteria(this.toDotPath()).size(s) /** * Creates a criterion using the $exists operator. @@ -185,7 +186,7 @@ infix fun KProperty<*>.size(s: Int): Criteria = * @see Criteria.exists */ infix fun KProperty<*>.exists(b: Boolean): Criteria = - Criteria(asString(this)).exists(b) + Criteria(this.toDotPath()).exists(b) /** * Creates a criterion using the $type operator. @@ -196,7 +197,7 @@ infix fun KProperty<*>.exists(b: Boolean): Criteria = * @see Criteria.type */ infix fun KProperty<*>.type(t: Int): Criteria = - Criteria(asString(this)).type(t) + Criteria(this.toDotPath()).type(t) /** * Creates a criterion using the $type operator. @@ -207,7 +208,7 @@ infix fun KProperty<*>.type(t: Int): Criteria = * @see Criteria.type */ infix fun KProperty<*>.type(t: Collection): Criteria = - Criteria(asString(this)).type(*t.toTypedArray()) + Criteria(this.toDotPath()).type(*t.toTypedArray()) /** * Creates a criterion using the $type operator. @@ -218,7 +219,7 @@ infix fun KProperty<*>.type(t: Collection): Criteria = * @see Criteria.type */ fun KProperty<*>.type(vararg t: JsonSchemaObject.Type): Criteria = - Criteria(asString(this)).type(*t) + Criteria(this.toDotPath()).type(*t) /** * Creates a criterion using the $not meta operator which affects the clause directly following @@ -229,7 +230,7 @@ fun KProperty<*>.type(vararg t: JsonSchemaObject.Type): Criteria = * @see Criteria.not */ fun KProperty<*>.not(): Criteria = - Criteria(asString(this)).not() + Criteria(this.toDotPath()).not() /** * Creates a criterion using a $regex operator. @@ -240,7 +241,7 @@ fun KProperty<*>.not(): Criteria = * @see Criteria.regex */ infix fun KProperty.regex(re: String): Criteria = - Criteria(asString(this)).regex(re, null) + Criteria(this.toDotPath()).regex(re, null) /** * Creates a criterion using a $regex and $options operator. @@ -251,7 +252,7 @@ infix fun KProperty.regex(re: String): Criteria = * @see Criteria.regex */ fun KProperty.regex(re: String, options: String?): Criteria = - Criteria(asString(this)).regex(re, options) + Criteria(this.toDotPath()).regex(re, options) /** * Syntactical sugar for [isEqualTo] making obvious that we create a regex predicate. @@ -260,7 +261,7 @@ fun KProperty.regex(re: String, options: String?): Criteria = * @see Criteria.regex */ infix fun KProperty.regex(re: Regex): Criteria = - Criteria(asString(this)).regex(re.toPattern()) + Criteria(this.toDotPath()).regex(re.toPattern()) /** * Syntactical sugar for [isEqualTo] making obvious that we create a regex predicate. @@ -269,7 +270,7 @@ infix fun KProperty.regex(re: Regex): Criteria = * @see Criteria.regex */ infix fun KProperty.regex(re: Pattern): Criteria = - Criteria(asString(this)).regex(re) + Criteria(this.toDotPath()).regex(re) /** * Syntactical sugar for [isEqualTo] making obvious that we create a regex predicate. @@ -278,7 +279,7 @@ infix fun KProperty.regex(re: Pattern): Criteria = * @see Criteria.regex */ infix fun KProperty.regex(re: BsonRegularExpression): Criteria = - Criteria(asString(this)).regex(re) + Criteria(this.toDotPath()).regex(re) /** * Creates a geospatial criterion using a $geoWithin $centerSphere operation. This is only available for @@ -294,7 +295,7 @@ infix fun KProperty.regex(re: BsonRegularExpression): Criteria = * @see Criteria.withinSphere */ infix fun KProperty>.withinSphere(circle: Circle): Criteria = - Criteria(asString(this)).withinSphere(circle) + Criteria(this.toDotPath()).withinSphere(circle) /** * Creates a geospatial criterion using a $geoWithin operation. @@ -306,7 +307,7 @@ infix fun KProperty>.withinSphere(circle: Circle): Criteria = * @see Criteria.within */ infix fun KProperty>.within(shape: Shape): Criteria = - Criteria(asString(this)).within(shape) + Criteria(this.toDotPath()).within(shape) /** * Creates a geospatial criterion using a $near operation. @@ -317,7 +318,7 @@ infix fun KProperty>.within(shape: Shape): Criteria = * @see Criteria.near */ infix fun KProperty>.near(point: Point): Criteria = - Criteria(asString(this)).near(point) + Criteria(this.toDotPath()).near(point) /** * Creates a geospatial criterion using a $nearSphere operation. This is only available for Mongo 1.7 and @@ -330,7 +331,7 @@ infix fun KProperty>.near(point: Point): Criteria = * @see Criteria.nearSphere */ infix fun KProperty>.nearSphere(point: Point): Criteria = - Criteria(asString(this)).nearSphere(point) + Criteria(this.toDotPath()).nearSphere(point) /** * Creates criterion using `$geoIntersects` operator which matches intersections of the given `geoJson` @@ -340,7 +341,7 @@ infix fun KProperty>.nearSphere(point: Point): Criteria = * @see Criteria.intersects */ infix fun KProperty>.intersects(geoJson: GeoJson<*>): Criteria = - Criteria(asString(this)).intersects(geoJson) + Criteria(this.toDotPath()).intersects(geoJson) /** * Creates a geo-spatial criterion using a $maxDistance operation, for use with $near @@ -352,7 +353,7 @@ infix fun KProperty>.intersects(geoJson: GeoJson<*>): Criteria = * @see Criteria.maxDistance */ infix fun KProperty>.maxDistance(d: Double): Criteria = - Criteria(asString(this)).maxDistance(d) + Criteria(this.toDotPath()).maxDistance(d) /** * Creates a geospatial criterion using a $minDistance operation, for use with $near or @@ -362,7 +363,7 @@ infix fun KProperty>.maxDistance(d: Double): Criteria = * @see Criteria.minDistance */ infix fun KProperty>.minDistance(d: Double): Criteria = - Criteria(asString(this)).minDistance(d) + Criteria(this.toDotPath()).minDistance(d) /** * Creates a geo-spatial criterion using a $maxDistance operation, for use with $near @@ -396,7 +397,7 @@ infix fun Criteria.minDistance(d: Double): Criteria = * @see Criteria.elemMatch */ infix fun KProperty<*>.elemMatch(c: Criteria): Criteria = - Criteria(asString(this)).elemMatch(c) + Criteria(this.toDotPath()).elemMatch(c) /** * Use [Criteria.BitwiseCriteriaOperators] as gateway to create a criterion using one of the @@ -412,4 +413,4 @@ infix fun KProperty<*>.elemMatch(c: Criteria): Criteria = * @see Criteria.bits */ infix fun KProperty<*>.bits(bitwiseCriteria: Criteria.BitwiseCriteriaOperators.() -> Criteria) = - Criteria(asString(this)).bits().let(bitwiseCriteria) + Criteria(this.toDotPath()).bits().let(bitwiseCriteria) diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java index 1ec266bac..ab65280a1 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/AbstractMongoConfigurationUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2022 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. @@ -26,7 +26,6 @@ import java.util.Collections; import java.util.Set; import org.junit.jupiter.api.Test; - import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -36,7 +35,6 @@ import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.core.convert.MongoTypeMapper; -import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; @@ -60,7 +58,8 @@ public class AbstractMongoConfigurationUnitTests { public void usesConfigClassPackageAsBaseMappingPackage() throws ClassNotFoundException { AbstractMongoClientConfiguration configuration = new SampleMongoConfiguration(); - assertThat(configuration.getMappingBasePackage()).isEqualTo(SampleMongoConfiguration.class.getPackage().getName()); + assertThat(configuration.getMappingBasePackages()) + .containsExactly(SampleMongoConfiguration.class.getPackage().getName()); assertThat(configuration.getInitialEntitySet()).hasSize(2); assertThat(configuration.getInitialEntitySet()).contains(Entity.class); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java index 4a934a960..8364fc220 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultIndexOperationsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2021 the original author or authors. + * Copyright 2014-2022 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. @@ -25,7 +25,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.mongodb.core.convert.QueryMapper; import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.index.IndexDefinition; import org.springframework.data.mongodb.core.index.IndexInfo; @@ -119,8 +118,7 @@ public class DefaultIndexOperationsIntegrationTests { IndexDefinition id = new Index().named("partial-with-inheritance").on("k3y", Direction.ASC) .partial(of(where("age").gte(10))); - indexOps = new DefaultIndexOperations(template.getMongoDbFactory(), COLLECTION_NAME, - new QueryMapper(template.getConverter()), MappingToSameCollection.class); + indexOps = new DefaultIndexOperations(template, COLLECTION_NAME, MappingToSameCollection.class); indexOps.ensureIndex(id); @@ -150,8 +148,7 @@ public class DefaultIndexOperationsIntegrationTests { IndexDefinition id = new Index().named("with-collation").on("xyz", Direction.ASC) .collation(Collation.of("de_AT").caseFirst(CaseFirst.off())); - new DefaultIndexOperations(template.getMongoDbFactory(), COLLECTION_NAME, new QueryMapper(template.getConverter()), - MappingToSameCollection.class); + new DefaultIndexOperations(template, COLLECTION_NAME, MappingToSameCollection.class); indexOps.ensureIndex(id); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java index 5a2e7e72b..8c20be176 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -141,7 +141,6 @@ public class MongoTemplateTests { cfg.configureMappingContext(it -> { it.autocreateIndex(false); it.initialEntitySet(AuditablePerson.class); - }); cfg.configureApplicationContext(it -> { @@ -178,7 +177,7 @@ public class MongoTemplateTests { }); }); - MongoDatabaseFactory factory = template.getMongoDbFactory(); + MongoDatabaseFactory factory = template.getMongoDatabaseFactory(); @AfterEach public void cleanUp() { @@ -2591,30 +2590,6 @@ public class MongoTemplateTests { assertThat(template.findOne(q, VersionedPerson.class)).isNull(); } - @Test // DATAMONGO-354, DATAMONGO-1824 - @MongoVersion(until = "3.6") - @SuppressWarnings("deprecation") - public void testUpdateShouldAllowMultiplePushAll() { - - DocumentWithMultipleCollections doc = new DocumentWithMultipleCollections(); - doc.id = "1234"; - doc.string1 = Arrays.asList("spring"); - doc.string2 = Arrays.asList("one"); - - template.save(doc); - - Update update = new Update().pushAll("string1", new Object[] { "data", "mongodb" }); - update.pushAll("string2", new String[] { "two", "three" }); - - Query findQuery = new Query(Criteria.where("id").is(doc.id)); - template.updateFirst(findQuery, update, DocumentWithMultipleCollections.class); - - DocumentWithMultipleCollections result = template.findOne(findQuery, DocumentWithMultipleCollections.class); - assertThat(result.string1).contains("spring", "data", "mongodb"); - assertThat(result.string2).contains("one", "two", "three"); - - } - @Test // DATAMONGO-404 public void updateWithPullShouldRemoveNestedItemFromDbRefAnnotatedCollection() { @@ -4029,9 +4004,7 @@ public class MongoTemplateTests { INSTANCE; public Date convert(LocalDateTime source) { - return source == null ? null : java.util.Date - .from(source.atZone(ZoneId.systemDefault()) - .toInstant()); + return source == null ? null : java.util.Date.from(source.atZone(ZoneId.systemDefault()).toInstant()); } } @@ -4040,8 +4013,7 @@ public class MongoTemplateTests { INSTANCE; public LocalDateTime convert(Date source) { - return source == null ? null : LocalDateTime.ofInstant( - source.toInstant(), ZoneId.systemDefault()); + return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java index 0a729f673..1bdf17772 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -51,7 +51,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; - import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; @@ -92,7 +91,6 @@ import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent; import org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback; import org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent; -import org.springframework.data.mongodb.core.mapreduce.GroupBy; import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions; import org.springframework.data.mongodb.core.query.BasicQuery; import org.springframework.data.mongodb.core.query.Collation; @@ -958,7 +956,7 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { @Test // DATAMONGO-2027 void mapReduceShouldNotUseOutputCollectionForInline() { - template.mapReduce("", "", "", MapReduceOptions.options().outputCollection("out-collection").outputTypeInline(), + template.mapReduce("", "", "", MapReduceOptions.options().actionInline().outputCollection("out-collection"), AutogenerateableId.class); verify(mapReduceIterable, never()).collectionName(any()); @@ -967,7 +965,7 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { @Test // DATAMONGO-2027 void mapReduceShouldUseOutputActionWhenPresent() { - template.mapReduce("", "", "", MapReduceOptions.options().outputCollection("out-collection").outputTypeMerge(), + template.mapReduce("", "", "", MapReduceOptions.options().actionMerge().outputCollection("out-collection"), AutogenerateableId.class); verify(mapReduceIterable).action(eq(MapReduceAction.MERGE)); @@ -977,7 +975,7 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { void mapReduceShouldUseOutputDatabaseWhenPresent() { template.mapReduce("", "", "", - MapReduceOptions.options().outputDatabase("out-database").outputCollection("out-collection").outputTypeMerge(), + MapReduceOptions.options().outputDatabase("out-database").outputCollection("out-collection"), AutogenerateableId.class); verify(mapReduceIterable).databaseName(eq("out-database")); @@ -986,8 +984,7 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { @Test // DATAMONGO-2027 void mapReduceShouldNotUseOutputDatabaseForInline() { - template.mapReduce("", "", "", MapReduceOptions.options().outputDatabase("out-database").outputTypeInline(), - AutogenerateableId.class); + template.mapReduce("", "", "", MapReduceOptions.options().outputDatabase("out-database"), AutogenerateableId.class); verify(mapReduceIterable, never()).databaseName(any()); } @@ -1001,20 +998,6 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { verify(aggregateIterable).collation(eq(com.mongodb.client.model.Collation.builder().locale("fr").build())); } - @Test // DATAMONGO-1518 - void groupShouldUseCollationWhenPresent() { - - commandResultDocument.append("retval", Collections.emptySet()); - template.group("collection-1", GroupBy.key("id").reduceFunction("bar").collation(Collation.of("fr")), - AutogenerateableId.class); - - ArgumentCaptor cmd = ArgumentCaptor.forClass(Document.class); - verify(db).runCommand(cmd.capture(), any(Class.class)); - - assertThat(cmd.getValue().get("group", Document.class).get("collation", Document.class)) - .isEqualTo(new Document("locale", "fr")); - } - @Test // DATAMONGO-1880 void countShouldUseCollationWhenPresent() { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java index 73f87618b..5eea906cb 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/QueryCursorPreparerUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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,8 +19,6 @@ import static org.mockito.Mockito.*; import static org.springframework.data.mongodb.core.query.Criteria.*; import static org.springframework.data.mongodb.core.query.Query.*; -import java.util.concurrent.TimeUnit; - import org.bson.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,7 +27,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; - import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.MongoTemplate.QueryCursorPreparer; import org.springframework.data.mongodb.core.query.BasicQuery; @@ -96,15 +93,6 @@ class QueryCursorPreparerUnitTests { verify(cursor).hint(new Document("age", 1)); } - @Test // DATAMONGO-957 - void appliesMaxTimeCorrectly() { - - Query query = query(where("foo").is("bar")).maxTime(1, TimeUnit.SECONDS); - prepare(query); - - verify(cursor).maxTime(1000, TimeUnit.MILLISECONDS); - } - @Test // DATAMONGO-957 void appliesCommentCorrectly() { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java index 87b314fa0..ae52c56f7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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. @@ -51,7 +51,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; - import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.dao.DataIntegrityViolationException; @@ -1004,14 +1003,14 @@ public class ReactiveMongoTemplateTests { IndexOperationsAdapter.blocking(template.indexOps(Venue.class)) .ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D)); - NearQuery geoFar = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).maxDistance(150, Metrics.KILOMETERS); + NearQuery geoFar = NearQuery.near(-73, 40, Metrics.KILOMETERS).limit(10).maxDistance(150, Metrics.KILOMETERS); template.geoNear(geoFar, Venue.class) // .as(StepVerifier::create) // .expectNextCount(4) // .verifyComplete(); - NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).maxDistance(120, Metrics.KILOMETERS); + NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).limit(10).maxDistance(120, Metrics.KILOMETERS); template.geoNear(geoNear, Venue.class) // .as(StepVerifier::create) // diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTransactionTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTransactionTests.java index 05f5a7c85..b4880228f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTransactionTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReactiveMongoTemplateTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -31,12 +31,17 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.reactivestreams.Publisher; import org.springframework.data.domain.Sort; +import org.springframework.data.mongodb.ReactiveMongoTransactionManager; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.test.util.Client; import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion; import org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable; import org.springframework.data.mongodb.test.util.MongoClientExtension; import org.springframework.data.mongodb.test.util.MongoTestUtils; +import org.springframework.transaction.ReactiveTransaction; +import org.springframework.transaction.reactive.TransactionCallback; +import org.springframework.transaction.reactive.TransactionalOperator; +import org.springframework.transaction.support.DefaultTransactionDefinition; import com.mongodb.ClientSessionOptions; import com.mongodb.reactivestreams.client.ClientSession; @@ -123,8 +128,7 @@ public class ReactiveMongoTemplateTransactionTests { @Test // DATAMONGO-1970 public void reactiveTransactionsCommitOnComplete() { - template.inTransaction().execute(action -> action.remove(ID_QUERY, Document.class, COLLECTION_NAME)) // - .as(StepVerifier::create) // + initTx().transactional(template.remove(ID_QUERY, Document.class, COLLECTION_NAME)).as(StepVerifier::create) // .expectNextCount(1) // .verifyComplete(); @@ -137,11 +141,10 @@ public class ReactiveMongoTemplateTransactionTests { @Test // DATAMONGO-1970 public void reactiveTransactionsAbortOnError() { - template.inTransaction().execute(action -> { - return action.remove(ID_QUERY, Document.class, COLLECTION_NAME).flatMap(result -> Mono.fromSupplier(() -> { - throw new RuntimeException("¯\\_(ツ)_/¯"); - })); - }).as(StepVerifier::create) // + initTx().transactional( + template.remove(ID_QUERY, Document.class, COLLECTION_NAME).flatMap(result -> Mono.fromSupplier(() -> { + throw new RuntimeException("¯\\_(ツ)_/¯"); + }))).as(StepVerifier::create) // .expectError() // .verify(); @@ -166,32 +169,19 @@ public class ReactiveMongoTemplateTransactionTests { .verifyComplete(); } - @Test // DATAMONGO-1970 - public void inTransactionCommitsProvidedTransactionalSession() { - - ClientSession session = Mono.from(client.startSession()).block(); - - session.startTransaction(); - - template.inTransaction(Mono.just(session)).execute(action -> { - return action.remove(ID_QUERY, Document.class, COLLECTION_NAME); - }) // - .as(StepVerifier::create) // - .expectNextCount(1) // - .verifyComplete(); - - assertThat(session.hasActiveTransaction()).isFalse(); - } - @Test // DATAMONGO-1970 public void changesNotVisibleOutsideTransaction() { - template.inTransaction().execute(action -> { - return action.remove(ID_QUERY, Document.class, COLLECTION_NAME).flatMapMany(val -> { + initTx().execute(new TransactionCallback<>() { + @Override + public Publisher doInTransaction(ReactiveTransaction status) { + return template.remove(ID_QUERY, Document.class, COLLECTION_NAME).flatMapMany(val -> { - // once we use the collection directly we're no longer participating in the tx - return template.getCollection(COLLECTION_NAME).flatMapMany(it -> it.find(ID_QUERY.getQueryObject())); - }); + // once we use the collection directly we're no longer participating in the tx + return client.getDatabase(DATABASE_NAME).getCollection(COLLECTION_NAME).find(ID_QUERY.getQueryObject()) + .first(); + }); + } }).as(StepVerifier::create).expectNext(DOCUMENT).verifyComplete(); template.exists(ID_QUERY, COLLECTION_NAME) // @@ -203,7 +193,7 @@ public class ReactiveMongoTemplateTransactionTests { @Test // DATAMONGO-1970 public void executeCreatesNewTransaction() { - ReactiveSessionScoped sessionScoped = template.inTransaction(); + ReactiveSessionScoped sessionScoped = template.withSession(client.startSession()); sessionScoped.execute(action -> { return action.remove(ID_QUERY, Document.class, COLLECTION_NAME); @@ -233,10 +223,9 @@ public class ReactiveMongoTemplateTransactionTests { @Test // DATAMONGO-1970 public void takeDoesNotAbortTransaction() { - template.inTransaction().execute(action -> { - return action.find(query(where("age").exists(true)).with(Sort.by("age")), Person.class).take(3) - .flatMap(action::remove); - }) // + initTx() + .transactional(template.find(query(where("age").exists(true)).with(Sort.by("age")), Person.class).take(3) + .flatMap(template::remove)) // .as(StepVerifier::create) // .expectNextCount(3) // .verifyComplete(); @@ -250,19 +239,23 @@ public class ReactiveMongoTemplateTransactionTests { @Test // DATAMONGO-1970 public void errorInFlowOutsideTransactionDoesNotAbortIt() { - template.inTransaction().execute(action -> { + initTx().execute(new TransactionCallback<>() { + @Override + public Publisher doInTransaction(ReactiveTransaction status) { + return template.find(query(where("age").is(22)).with(Sort.by("age")), Person.class).buffer(2) + .flatMap(values -> { - return action.find(query(where("age").is(22)).with(Sort.by("age")), Person.class).buffer(2).flatMap(values -> { - - return action.remove(query(where("id").in(values.stream().map(Person::getId).collect(Collectors.toList()))), - Person.class).then(Mono.just(values)); - }); - }).flatMap(deleted -> { - throw new RuntimeException("error outside the transaction does not influence it."); - }) // - .as(StepVerifier::create) // - .expectError() // - .verify(); + return template + .remove(query(where("id").in(values.stream().map(Person::getId).collect(Collectors.toList()))), + Person.class) + .then(Mono.just(values)); + }); + } + }).collectList() // completes the above computation + .flatMap(deleted -> { + throw new RuntimeException("error outside the transaction does not influence it."); + }).as(StepVerifier::create) // + .verifyError(); template.count(query(where("age").exists(true)), Person.class) // .as(StepVerifier::create) // @@ -278,7 +271,7 @@ public class ReactiveMongoTemplateTransactionTests { PersonWithVersionPropertyOfTypeInteger saved = template.insert(rojer).block(); - template.inTransaction().execute(action -> action.remove(saved)) // + initTx().transactional(template.remove(saved)) // .as(StepVerifier::create) // .consumeNextWith(result -> assertThat(result.getDeletedCount()).isOne()) // .verifyComplete(); @@ -293,7 +286,7 @@ public class ReactiveMongoTemplateTransactionTests { PersonWithVersionPropertyOfTypeInteger saved = template.insert(rojer).block(); saved.version = 5; - template.inTransaction().execute(action -> action.remove(saved)) // + initTx().transactional(template.remove(saved)) // .as(StepVerifier::create) // .consumeNextWith(actual -> { @@ -310,9 +303,15 @@ public class ReactiveMongoTemplateTransactionTests { rojer.firstName = "rojer"; rojer.version = 5; - template.inTransaction().execute(action -> action.remove(rojer)) // + initTx().transactional(template.remove(rojer)) // .as(StepVerifier::create) // .consumeNextWith(result -> assertThat(result.getDeletedCount()).isZero()) // .verifyComplete(); } + + TransactionalOperator initTx() { + + ReactiveMongoTransactionManager txmgr = new ReactiveMongoTransactionManager(template.getMongoDatabaseFactory()); + return TransactionalOperator.create(txmgr, new DefaultTransactionDefinition()); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SessionBoundMongoTemplateUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SessionBoundMongoTemplateUnitTests.java index 4cc5ae28a..6f41e2c9f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SessionBoundMongoTemplateUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SessionBoundMongoTemplateUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -40,7 +40,6 @@ import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; -import org.springframework.data.mongodb.core.mapreduce.GroupBy; import org.springframework.data.mongodb.core.query.NearQuery; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; @@ -270,17 +269,6 @@ public class SessionBoundMongoTemplateUnitTests { verify(collection).aggregate(eq(clientSession), anyList(), eq(Document.class)); } - @Test // DATAMONGO-1880 - public void groupShouldUseProxiedDatabase() { - - when(database.runCommand(any(ClientSession.class), any(), eq(Document.class))) - .thenReturn(new Document("retval", Collections.emptyList())); - - template.group(COLLECTION_NAME, GroupBy.key("firstName"), Person.class); - - verify(database).runCommand(eq(clientSession), any(), eq(Document.class)); - } - @Test // DATAMONGO-1880 public void mapReduceShouldUseProxiedCollection() { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java index a7ab1c99f..bda1f0f22 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -16,6 +16,7 @@ package org.springframework.data.mongodb.core; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; @@ -54,8 +55,8 @@ public class TestMongoConfiguration extends AbstractMongoClientConfiguration { } @Override - public String getMappingBasePackage() { - return MongoMappingContext.class.getPackage().getName(); + protected Collection getMappingBasePackages() { + return Collections.singleton(MongoMappingContext.class.getPackage().getName()); } @Override diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/AggregationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/AggregationTests.java index b7663ba3a..456b95817 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/AggregationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/AggregationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -1426,7 +1426,7 @@ public class AggregationTests { mongoTemplate.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location")); - NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).limit(10).maxDistance(150); Aggregation agg = newAggregation(Aggregation.geoNear(geoNear, "distance")); AggregationResults result = mongoTemplate.aggregate(agg, Venue.class, Document.class); @@ -1448,7 +1448,7 @@ public class AggregationTests { mongoTemplate.indexOps(Venue.class) .ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE)); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).limit(10).maxDistance(150); Aggregation agg = newAggregation(Aggregation.geoNear(geoNear, "distance")); AggregationResults result = mongoTemplate.aggregate(agg, Venue.class, Document.class); @@ -1470,7 +1470,7 @@ public class AggregationTests { mongoTemplate.indexOps(Venue.class) .ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE)); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).num(10).maxDistance(150) + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).limit(10).maxDistance(150) .inMiles(); Aggregation agg = newAggregation(Aggregation.geoNear(geoNear, "distance")); @@ -1684,7 +1684,7 @@ public class AggregationTests { mongoTemplate.insert(Arrays.asList(sales1, sales2, sales3), Sales.class); TypedAggregation agg = newAggregation(Sales.class, project().and("items") - .filter("item", AggregationFunctionExpressions.GTE.of(field("item.price"), 100)).as("items")); + .filter("item", ComparisonOperators.valueOf("item.price").greaterThanEqualToValue(100)).as("items")); assertThat(mongoTemplate.aggregate(agg, Sales.class).getMappedResults()).contains( Sales.builder().id("0").items(Collections.singletonList(item2)).build(), @@ -1701,14 +1701,14 @@ public class AggregationTests { mongoTemplate.insert(Arrays.asList(sales1, sales2), Sales2.class); ExpressionVariable total = ExpressionVariable.newVariable("total") - .forExpression(AggregationFunctionExpressions.ADD.of(Fields.field("price"), Fields.field("tax"))); + .forExpression(ArithmeticOperators.valueOf("price").sum().and("tax")); ExpressionVariable discounted = ExpressionVariable.newVariable("discounted") .forExpression(ConditionalOperators.Cond.when("applyDiscount").then(0.9D).otherwise(1.0D)); TypedAggregation agg = Aggregation.newAggregation(Sales2.class, Aggregation.project() .and(VariableOperators.Let.define(total, discounted).andApply( - AggregationFunctionExpressions.MULTIPLY.of(Fields.field("total"), Fields.field("discounted")))) + ArithmeticOperators.valueOf("total").multiplyBy("discounted"))) .as("finalTotal")); AggregationResults result = mongoTemplate.aggregate(agg, Document.class); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/FilterExpressionUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/FilterExpressionUnitTests.java index a318a5559..30a394dff 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/FilterExpressionUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/FilterExpressionUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016. the original author or authors. + * Copyright 2016-2022 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. @@ -25,12 +25,8 @@ import org.bson.Document; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; - -import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.DocumentTestUtils; -import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.NoOpDbRefResolver; import org.springframework.data.mongodb.core.convert.QueryMapper; @@ -58,7 +54,7 @@ class FilterExpressionUnitTests { TypedAggregation agg = Aggregation.newAggregation(Sales.class, Aggregation.project() - .and(filter("items").as("item").by(AggregationFunctionExpressions.GTE.of(Fields.field("item.price"), 100))) + .and(filter("items").as("item").by(ComparisonOperators.valueOf("item.price").greaterThanEqualToValue(100))) .as("items")); Document $filter = extractFilterOperatorFromDocument(agg.toDocument("sales", aggregationContext)); @@ -75,7 +71,7 @@ class FilterExpressionUnitTests { void shouldConstructFilterExpressionCorrectlyWhenUsingFilterOnProjectionBuilder() { TypedAggregation agg = Aggregation.newAggregation(Sales.class, Aggregation.project().and("items") - .filter("item", AggregationFunctionExpressions.GTE.of(Fields.field("item.price"), 100)).as("items")); + .filter("item", ComparisonOperators.valueOf("item.price").greaterThanEqualToValue(100)).as("items")); Document $filter = extractFilterOperatorFromDocument(agg.toDocument("sales", aggregationContext)); Document expected = Document.parse("{" + // @@ -92,7 +88,7 @@ class FilterExpressionUnitTests { TypedAggregation agg = Aggregation.newAggregation(Sales.class, Aggregation.project().and(filter(Arrays. asList(1, "a", 2, null, 3.1D, 4, "5")).as("num") - .by(AggregationFunctionExpressions.GTE.of(Fields.field("num"), 3))).as("items")); + .by(ComparisonOperators.valueOf("num").greaterThanEqualToValue(3))).as("items")); Document $filter = extractFilterOperatorFromDocument(agg.toDocument("sales", aggregationContext)); Document expected = Document.parse("{" + // diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/GroupOperationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/GroupOperationUnitTests.java index e63aa9ca8..a0bdf2ddc 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/GroupOperationUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/GroupOperationUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -16,11 +16,9 @@ package org.springframework.data.mongodb.core.aggregation; import static org.assertj.core.api.Assertions.*; -import static org.springframework.data.mongodb.core.aggregation.AggregationFunctionExpressions.*; import static org.springframework.data.mongodb.core.aggregation.Fields.*; import java.util.Arrays; -import java.util.Collections; import org.bson.Document; import org.junit.jupiter.api.Test; @@ -85,8 +83,7 @@ class GroupOperationUnitTests { Document groupClause = extractDocumentFromGroupOperation(operation); Document idClause = DocumentTestUtils.getAsDocument(groupClause, UNDERSCORE_ID); - assertThat(idClause).containsEntry("a", "$a") - .containsEntry("b", "$c"); + assertThat(idClause).containsEntry("a", "$a").containsEntry("b", "$c"); } @Test @@ -186,15 +183,13 @@ class GroupOperationUnitTests { GroupOperation groupOperation = Aggregation // .group("username") // - .first(SIZE.of(field("tags"))) // + .first(ArrayOperators.arrayOf("tags").length()) // .as("tags_count"); Document groupClause = extractDocumentFromGroupOperation(groupOperation); Document tagsCount = DocumentTestUtils.getAsDocument(groupClause, "tags_count"); - assertThat(tagsCount) - .containsEntry("$first", new Document("$size", Collections - .singletonList("$tags"))); + assertThat(tagsCount).containsEntry("$first", new Document("$size", "$tags")); } @Test // DATAMONGO-1327 diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperationUnitTests.java index 9ef207c9a..a299bdc52 100755 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperationUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperationUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2021 the original author or authors. + * Copyright 2013-2022 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. @@ -17,7 +17,6 @@ package org.springframework.data.mongodb.core.aggregation; import static org.assertj.core.api.Assertions.*; import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; -import static org.springframework.data.mongodb.core.aggregation.AggregationFunctionExpressions.*; import static org.springframework.data.mongodb.core.aggregation.Fields.*; import static org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable.*; import static org.springframework.data.mongodb.test.util.Assertions.assertThat; @@ -29,7 +28,6 @@ import java.util.List; import org.bson.Document; import org.junit.jupiter.api.Test; - import org.springframework.data.domain.Range; import org.springframework.data.domain.Range.Bound; import org.springframework.data.mongodb.core.DocumentTestUtils; @@ -380,13 +378,13 @@ public class ProjectionOperationUnitTests { ProjectionOperation operation = Aggregation // .project() // - .and(SIZE.of(field("tags"))) // + .and(ArrayOperators.arrayOf("tags").length()) // .as("tags_count"); Document document = operation.toDocument(Aggregation.DEFAULT_CONTEXT); Document projected = extractOperation("$project", document); - assertThat(projected.get("tags_count")).isEqualTo(new Document("$size", Arrays.asList("$tags"))); + assertThat(projected.get("tags_count")).isEqualTo(new Document("$size", "$tags")); } @Test // DATAMONGO-1457 @@ -626,9 +624,8 @@ public class ProjectionOperationUnitTests { void shouldRenderAbsAggregationExpresssion() { Document agg = project() - .and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).abs()) - .as("delta").toDocument(Aggregation.DEFAULT_CONTEXT); + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).abs()).as("delta") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { delta: { $abs: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -654,9 +651,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderCeilAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).ceil()) - .as("delta").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).ceil()).as("delta") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { delta: { $ceil: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -665,8 +662,7 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderDivide() { - Document agg = project().and("value") - .divide(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).as("result") + Document agg = project().and("value").divide(ArithmeticOperators.valueOf("start").subtract("end")).as("result") .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo( @@ -677,8 +673,7 @@ public class ProjectionOperationUnitTests { void shouldRenderDivideAggregationExpresssion() { Document agg = project() - .and(ArithmeticOperators.valueOf("anyNumber") - .divideBy(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end")))) + .and(ArithmeticOperators.valueOf("anyNumber").divideBy(ArithmeticOperators.valueOf("start").subtract("end"))) .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document @@ -697,9 +692,8 @@ public class ProjectionOperationUnitTests { void shouldRenderExpAggregationExpresssion() { Document agg = project() - .and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).exp()) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).exp()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $exp: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -716,9 +710,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderFloorAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).floor()) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).floor()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $floor: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -735,8 +729,7 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderLnAggregationExpresssion() { - Document agg = project() - .and(ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).ln()) + Document agg = project().and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).ln()) .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) @@ -754,9 +747,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderLogAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).log(2)) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).log(2)).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $log: [ { $subtract: [ \"$start\", \"$end\" ] }, 2] } }}")); @@ -773,9 +766,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderLog10AggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).log10()) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).log10()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $log10: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -784,8 +777,8 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderMod() { - Document agg = project().and("value").mod(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project().and("value").mod(ArithmeticOperators.valueOf("start").subtract("end")).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo( Document.parse("{ $project: { result: { $mod: [\"$value\", { $subtract: [ \"$start\", \"$end\" ] }] } }}")); @@ -794,9 +787,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderModAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).mod(2)) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).mod(2)).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $mod: [{ $subtract: [ \"$start\", \"$end\" ] }, 2] } }}")); @@ -805,8 +798,7 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderMultiply() { - Document agg = project().and("value") - .multiply(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).as("result") + Document agg = project().and("value").multiply(ArithmeticOperators.valueOf("start").subtract("end")).as("result") .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document @@ -816,10 +808,8 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderMultiplyAggregationExpresssion() { - Document agg = project() - .and(ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))) - .multiplyBy(2).multiplyBy("refToAnotherNumber")) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project().and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")) + .multiplyBy(2).multiplyBy("refToAnotherNumber")).as("result").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document.parse( "{ $project: { result: { $multiply: [{ $subtract: [ \"$start\", \"$end\" ] }, 2, \"$refToAnotherNumber\"] } }}")); @@ -836,9 +826,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderPowAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).pow(2)) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).pow(2)).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $pow: [{ $subtract: [ \"$start\", \"$end\" ] }, 2] } }}")); @@ -855,9 +845,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderSqrtAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).sqrt()) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).sqrt()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $sqrt: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -866,23 +856,22 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderSubtract() { - Document agg = project().and("numericField").minus(AggregationFunctionExpressions.SIZE.of(field("someArray"))) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project().and("numericField").minus(ArrayOperators.arrayOf("someArray").length()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo( - Document.parse("{ $project: { result: { $subtract: [ \"$numericField\", { $size : [\"$someArray\"]}] } } }")); + Document.parse("{ $project: { result: { $subtract: [ \"$numericField\", { $size : \"$someArray\"}] } } }")); } @Test // DATAMONGO-1536 void shouldRenderSubtractAggregationExpresssion() { Document agg = project() - .and(ArithmeticOperators.valueOf("numericField") - .subtract(AggregationFunctionExpressions.SIZE.of(field("someArray")))) + .and(ArithmeticOperators.valueOf("numericField").subtract(ArrayOperators.arrayOf("someArray").length())) .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo( - Document.parse("{ $project: { result: { $subtract: [ \"$numericField\", { $size : [\"$someArray\"]}] } } }")); + Document.parse("{ $project: { result: { $subtract: [ \"$numericField\", { $size : \"$someArray\"}] } } }")); } @Test // DATAMONGO-1536 @@ -896,9 +885,9 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1536 void shouldRenderTruncAggregationExpresssion() { - Document agg = project().and( - ArithmeticOperators.valueOf(AggregationFunctionExpressions.SUBTRACT.of(field("start"), field("end"))).trunc()) - .as("result").toDocument(Aggregation.DEFAULT_CONTEXT); + Document agg = project() + .and(ArithmeticOperators.valueOf(ArithmeticOperators.valueOf("start").subtract("end")).trunc()).as("result") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg) .isEqualTo(Document.parse("{ $project: { result: { $trunc: { $subtract: [ \"$start\", \"$end\" ] } } }}")); @@ -1591,8 +1580,7 @@ public class ProjectionOperationUnitTests { void shouldRenderMapAggregationExpression() { Document agg = Aggregation.project() - .and(VariableOperators.mapItemsOf("quizzes").as("grade") - .andApply(AggregationFunctionExpressions.ADD.of(field("grade"), 2))) + .and(VariableOperators.mapItemsOf("quizzes").as("grade").andApply(ArithmeticOperators.valueOf("grade").add(2))) .as("adjustedGrades").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document.parse( @@ -1603,12 +1591,12 @@ public class ProjectionOperationUnitTests { void shouldRenderMapAggregationExpressionOnExpression() { Document agg = Aggregation.project() - .and(VariableOperators.mapItemsOf(AggregationFunctionExpressions.SIZE.of("foo")).as("grade") - .andApply(AggregationFunctionExpressions.ADD.of(field("grade"), 2))) + .and(VariableOperators.mapItemsOf(ArrayOperators.arrayOf("foo").length()).as("grade") + .andApply(ArithmeticOperators.valueOf("grade").add(2))) .as("adjustedGrades").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document.parse( - "{ $project:{ adjustedGrades:{ $map: { input: { $size : [\"foo\"]}, as: \"grade\",in: { $add: [ \"$$grade\", 2 ] }}}}}")); + "{ $project:{ adjustedGrades:{ $map: { input: { $size : \"$foo\"}, as: \"grade\",in: { $add: [ \"$$grade\", 2 ] }}}}}")); } @Test // DATAMONGO-861, DATAMONGO-1542 @@ -1648,12 +1636,10 @@ public class ProjectionOperationUnitTests { Document agg = Aggregation.project() .and(VariableOperators - .define( - newVariable("total") - .forExpression(AggregationFunctionExpressions.ADD.of(Fields.field("price"), Fields.field("tax"))), + .define(newVariable("total").forExpression(ArithmeticOperators.valueOf("price").add("tax")), newVariable("discounted") .forExpression(ConditionalOperators.Cond.when("applyDiscount").then(0.9D).otherwise(1.0D))) - .andApply(AggregationFunctionExpressions.MULTIPLY.of(Fields.field("total"), Fields.field("discounted")))) // + .andApply(ArithmeticOperators.valueOf("total").multiplyBy("discounted"))) // .as("finalTotal").toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document.parse("{ $project:{ \"finalTotal\" : { \"$let\": {" + // @@ -1668,16 +1654,14 @@ public class ProjectionOperationUnitTests { @Test // DATAMONGO-1538 void shouldRenderLetExpressionCorrectlyWhenUsingLetOnProjectionBuilder() { - ExpressionVariable var1 = newVariable("total") - .forExpression(AggregationFunctionExpressions.ADD.of(Fields.field("price"), Fields.field("tax"))); + ExpressionVariable var1 = newVariable("total").forExpression(ArithmeticOperators.valueOf("price").add("tax")); ExpressionVariable var2 = newVariable("discounted") .forExpression(ConditionalOperators.Cond.when("applyDiscount").then(0.9D).otherwise(1.0D)); Document agg = Aggregation.project().and("foo") - .let(Arrays.asList(var1, var2), - AggregationFunctionExpressions.MULTIPLY.of(Fields.field("total"), Fields.field("discounted"))) - .as("finalTotal").toDocument(Aggregation.DEFAULT_CONTEXT); + .let(Arrays.asList(var1, var2), ArithmeticOperators.valueOf("total").multiplyBy("discounted")).as("finalTotal") + .toDocument(Aggregation.DEFAULT_CONTEXT); assertThat(agg).isEqualTo(Document.parse("{ $project:{ \"finalTotal\" : { \"$let\": {" + // "\"vars\": {" + // @@ -1774,7 +1758,8 @@ public class ProjectionOperationUnitTests { Document agg = project().and(StringOperators.valueOf("field1").regexFind("e")).as("regex") .toDocument(Aggregation.DEFAULT_CONTEXT); - assertThat(agg).isEqualTo(Document.parse("{ $project : { regex: { $regexFind: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); + assertThat(agg).isEqualTo( + Document.parse("{ $project : { regex: { $regexFind: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); } @Test // GH-3725 @@ -1783,7 +1768,8 @@ public class ProjectionOperationUnitTests { Document agg = project().and(StringOperators.valueOf("field1").regexFindAll("e")).as("regex") .toDocument(Aggregation.DEFAULT_CONTEXT); - assertThat(agg).isEqualTo(Document.parse("{ $project : { regex: { $regexFindAll: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); + assertThat(agg).isEqualTo( + Document.parse("{ $project : { regex: { $regexFindAll: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); } @Test // GH-3725 @@ -1792,7 +1778,8 @@ public class ProjectionOperationUnitTests { Document agg = project().and(StringOperators.valueOf("field1").regexMatch("e")).as("regex") .toDocument(Aggregation.DEFAULT_CONTEXT); - assertThat(agg).isEqualTo(Document.parse("{ $project : { regex: { $regexMatch: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); + assertThat(agg).isEqualTo( + Document.parse("{ $project : { regex: { $regexMatch: { \"input\" : \"$field1\", \"regex\" : \"e\" } } } }")); } @Test // DATAMONGO-1548 diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceRootOperationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceRootOperationUnitTests.java index 9fbc36586..8fcf4355c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceRootOperationUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceRootOperationUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 the original author or authors. + * Copyright 2016-2022 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,7 +19,6 @@ import static org.assertj.core.api.Assertions.*; import org.bson.Document; import org.junit.jupiter.api.Test; - import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootDocumentOperation; /** @@ -55,7 +54,7 @@ class ReplaceRootOperationUnitTests { ReplaceRootOperation operation = new ReplaceRootOperation(VariableOperators // .mapItemsOf("array") // .as("element") // - .andApply(AggregationFunctionExpressions.MULTIPLY.of("$$element", 10))); + .andApply(ArithmeticOperators.valueOf("$$element").multiplyBy(10))); Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT); @@ -68,7 +67,7 @@ class ReplaceRootOperationUnitTests { ReplaceRootOperation operation = ReplaceRootDocumentOperation.builder().withDocument() // .andValue("value").as("key") // - .and(AggregationFunctionExpressions.MULTIPLY.of("$$element", 10)).as("multiply"); + .and(ArithmeticOperators.valueOf("$$element").multiplyBy(10)).as("multiply"); Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceWithOperationUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceWithOperationUnitTests.java index d1a21a254..fde90ae75 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceWithOperationUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/aggregation/ReplaceWithOperationUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2019-2021 the original author or authors. + * Copyright 2019-2022 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. @@ -47,7 +47,7 @@ class ReplaceWithOperationUnitTests { ReplaceWithOperation operation = ReplaceWithOperation.replaceWithValueOf(VariableOperators // .mapItemsOf("array") // .as("element") // - .andApply(AggregationFunctionExpressions.MULTIPLY.of("$$element", 10))); + .andApply(ArithmeticOperators.valueOf("$$element").multiplyBy(10))); Document dbObject = operation.toDocument(Aggregation.DEFAULT_CONTEXT); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/UpdateMapperUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/UpdateMapperUnitTests.java index 3e744f675..6cdd7b7f7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/UpdateMapperUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/UpdateMapperUnitTests.java @@ -37,7 +37,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; - import org.springframework.core.convert.converter.Converter; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; @@ -48,6 +47,8 @@ import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.data.mapping.MappingException; import org.springframework.data.mongodb.core.DocumentTestUtils; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; +import org.springframework.data.mongodb.core.convert.UpdateMapper; import org.springframework.data.mongodb.core.mapping.DocumentReference; import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; @@ -436,7 +437,7 @@ class UpdateMapperUnitTests { new NestedEntity("mongodb")); NestedEntity[] array = new NestedEntity[someValues.size()]; - Update update = new Update().pushAll("collectionOfNestedEntities", someValues.toArray(array)); + Update update = new Update().push("collectionOfNestedEntities").each(someValues.toArray(array)); mapper.getMappedObject(update.getUpdateObject(), context.getPersistentEntity(DomainEntity.class)); verify(writingConverterSpy, times(3)).convert(Mockito.any(NestedEntity.class)); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java index a5582e330..9ed8c9f27 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 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. @@ -28,7 +28,6 @@ import org.junit.After; import org.junit.Before; 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.data.geo.Box; @@ -112,15 +111,14 @@ public abstract class AbstractGeoSpatialTests { protected void addVenues() { - template.bulkOps(BulkMode.UNORDERED, Venue.class).insert(TestEntities.geolocation().newYork()).execute(); -// template.insertAll(TestEntities.geolocation().newYork()); + // template.insertAll(TestEntities.geolocation().newYork()); } @Test public void geoNear() { - NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).limit(10).maxDistance(150); GeoResults result = template.geoNear(geoNear, Venue.class); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java index 6fa053dac..4f087f093 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2021 the original author or authors. + * Copyright 2015-2022 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. @@ -120,7 +120,7 @@ public class GeoJsonTests { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).limit(10).maxDistance(150); GeoResults result = template.geoNear(geoNear, Venue2DSphere.class); @@ -134,7 +134,7 @@ public class GeoJsonTests { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).limit(10).maxDistance(150); GeoResults result = template.geoNear(geoNear, VenueWithDistanceField.class); @@ -153,7 +153,7 @@ public class GeoJsonTests { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).num(10).maxDistance(150); + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.KILOMETERS).limit(10).maxDistance(150); GeoResults result = template.geoNear(geoNear, Venue2DSphere.class, template.getCollectionName(Venue2DSphere.class), VenueWithDistanceField.class); @@ -172,7 +172,7 @@ public class GeoJsonTests { public void geoNearShouldReturnDistanceCorrectlyUsingGeoJson/*which is using the meters*/() { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73.99171, 40.738868), Metrics.KILOMETERS).num(10) + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73.99171, 40.738868), Metrics.KILOMETERS).limit(10) .maxDistance(0.4); GeoResults result = template.geoNear(geoNear, Venue2DSphere.class); @@ -188,7 +188,7 @@ public class GeoJsonTests { public void geoNearShouldReturnDistanceCorrectly/*which is using the meters*/() { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new Point(-73.99171, 40.738868), Metrics.KILOMETERS).num(10).maxDistance(0.4); + NearQuery geoNear = NearQuery.near(new Point(-73.99171, 40.738868), Metrics.KILOMETERS).limit(10).maxDistance(0.4); GeoResults result = template.geoNear(geoNear, Venue2DSphere.class); @@ -203,7 +203,7 @@ public class GeoJsonTests { public void geoNearWithMiles() { createIndexAndAddVenues(); - NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.MILES).num(10).maxDistance(93.2057); + NearQuery geoNear = NearQuery.near(new GeoJsonPoint(-73, 40), Metrics.MILES).limit(10).maxDistance(93.2057); GeoResults result = template.geoNear(geoNear, Venue2DSphere.class); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java index fe226ab9f..b847526fd 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -23,7 +23,6 @@ import static org.springframework.data.mongodb.core.query.Query.*; import java.util.List; import org.junit.Test; - import org.springframework.data.domain.Sort.Direction; import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.Metric; @@ -63,7 +62,7 @@ public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests { @Test // DATAMONGO-1110 public void geoNearWithMinDistance() { - NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1); + NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).limit(10).minDistance(1); GeoResults result = template.geoNear(geoNear, Venue.class); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolverUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolverUnitTests.java index 79f65d228..e7ce8d168 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolverUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexResolverUnitTests.java @@ -32,7 +32,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; - import org.springframework.core.annotation.AliasFor; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.annotation.Id; @@ -306,8 +305,8 @@ public class MongoPersistentEntityIndexResolverUnitTests { @Document("WithOptionsOnIndexedProperty") class WithOptionsOnIndexedProperty { - @Indexed(background = true, direction = IndexDirection.DESCENDING, dropDups = true, expireAfterSeconds = 10, - sparse = true, unique = true) // + @Indexed(background = true, direction = IndexDirection.DESCENDING, expireAfterSeconds = 10, sparse = true, + unique = true) // String indexedProperty; } @@ -319,8 +318,7 @@ public class MongoPersistentEntityIndexResolverUnitTests { class IndexOnLevelZeroWithExplicityNamedField { - @Indexed - @Field("customFieldName") String namedProperty; + @Indexed @Field("customFieldName") String namedProperty; } @Document @@ -428,8 +426,7 @@ public class MongoPersistentEntityIndexResolverUnitTests { @Document class IndexOnMetaAnnotatedField { - @Field("_name") - @IndexedFieldAnnotation String lastname; + @Field("_name") @IndexedFieldAnnotation String lastname; } /** @@ -1492,8 +1489,7 @@ public class MongoPersistentEntityIndexResolverUnitTests { @Document class SimilarityHolingBean { - @Indexed - @Field("norm") String normalProperty; + @Indexed @Field("norm") String normalProperty; @Field("similarityL") private List listOfSimilarilyNamedEntities = null; } @@ -1656,8 +1652,7 @@ public class MongoPersistentEntityIndexResolverUnitTests { @Document class WithHashedIndexOnId { - @HashIndexed - @Id String id; + @HashIndexed @Id String id; } @Document diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java index c18073d2b..8ddf7da36 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -15,6 +15,7 @@ */ package org.springframework.data.mongodb.core.mapping; +import java.util.Collection; import java.util.Collections; import java.util.Set; @@ -42,8 +43,8 @@ public class GeoIndexedAppConfig extends AbstractMongoClientConfiguration { } @Override - public String getMappingBasePackage() { - return "org.springframework.data.mongodb.core.core.mapping"; + protected Collection getMappingBasePackages() { + return Collections.singleton("org.springframework.data.mongodb.core.core.mapping"); } @Bean diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListenerUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListenerUnitTests.java deleted file mode 100644 index f52508524..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/AuditingEventListenerUnitTests.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2012-2021 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 - * - * https://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.mapping.event; - -import static org.assertj.core.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - -import lombok.AllArgsConstructor; -import lombok.NoArgsConstructor; -import lombok.Value; -import lombok.experimental.Wither; - -import java.util.Arrays; -import java.util.Date; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; - -import org.springframework.core.Ordered; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.auditing.IsNewAwareAuditingHandler; -import org.springframework.data.mapping.context.PersistentEntities; -import org.springframework.data.mongodb.core.mapping.MongoMappingContext; - -/** - * Unit tests for {@link AuditingEventListener}. - * - * @author Oliver Gierke - * @author Thomas Darimont - */ -@ExtendWith(MockitoExtension.class) -public class AuditingEventListenerUnitTests { - - private IsNewAwareAuditingHandler handler; - private AuditingEventListener listener; - - @BeforeEach - void setUp() { - - MongoMappingContext mappingContext = new MongoMappingContext(); - mappingContext.getPersistentEntity(Sample.class); - - handler = spy(new IsNewAwareAuditingHandler(new PersistentEntities(Arrays.asList(mappingContext)))); - listener = new AuditingEventListener(() -> handler); - } - - @Test // DATAMONGO-577 - void rejectsNullAuditingHandler() { - assertThatIllegalArgumentException().isThrownBy(() -> new AuditingEventListener(null)); - } - - @Test // DATAMONGO-577 - void triggersCreationMarkForObjectWithEmptyId() { - - Sample sample = new Sample(); - listener.onApplicationEvent(new BeforeConvertEvent(sample, "collection-1")); - - verify(handler, times(1)).markCreated(sample); - verify(handler, times(0)).markModified(any()); - } - - @Test // DATAMONGO-577 - void triggersModificationMarkForObjectWithSetId() { - - Sample sample = new Sample(); - sample.id = "id"; - listener.onApplicationEvent(new BeforeConvertEvent(sample, "collection-1")); - - verify(handler, times(0)).markCreated(any()); - verify(handler, times(1)).markModified(sample); - } - - @Test - void hasExplicitOrder() { - - assertThat(listener).isInstanceOf(Ordered.class); - assertThat(listener.getOrder()).isEqualTo(100); - } - - @Test // DATAMONGO-1992 - void propagatesChangedInstanceToEvent() { - - ImmutableSample sample = new ImmutableSample(); - BeforeConvertEvent event = new BeforeConvertEvent<>(sample, "collection"); - - ImmutableSample newSample = new ImmutableSample(); - IsNewAwareAuditingHandler handler = mock(IsNewAwareAuditingHandler.class); - doReturn(newSample).when(handler).markAudited(eq(sample)); - - AuditingEventListener listener = new AuditingEventListener(() -> handler); - listener.onApplicationEvent(event); - - assertThat(event.getSource()).isSameAs(newSample); - } - - static class Sample { - - @Id String id; - @CreatedDate Date created; - @LastModifiedDate Date modified; - } - - @Value - @Wither - @AllArgsConstructor - @NoArgsConstructor(force = true) - private static class ImmutableSample { - - @Id String id; - @CreatedDate Date created; - @LastModifiedDate Date modified; - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/GroupByTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/GroupByTests.java deleted file mode 100644 index 6aa7dd5ff..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/GroupByTests.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2011-2021 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 - * - * https://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.mapreduce; - -import static org.assertj.core.api.Assertions.*; -import static org.assertj.core.data.Offset.offset; -import static org.springframework.data.mongodb.core.mapreduce.GroupBy.*; -import static org.springframework.data.mongodb.core.query.Criteria.*; - -import org.bson.Document; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion; -import org.springframework.data.mongodb.test.util.MongoServerCondition; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import com.mongodb.client.MongoCollection; - -/** - * Integration tests for group-by operations. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Christoph Strobl - */ -@ExtendWith({ SpringExtension.class, MongoServerCondition.class }) -@EnableIfMongoServerVersion(isLessThan = "4.1") -@ContextConfiguration("classpath:infrastructure.xml") -public class GroupByTests { - - static final String GROUP_TEST_COLLECTION = "group_test_collection"; - - @Autowired MongoTemplate mongoTemplate; - - @BeforeEach - public void setUp() { - cleanDb(); - } - - protected void cleanDb() { - mongoTemplate.dropCollection(mongoTemplate.getCollectionName(XObject.class)); - mongoTemplate.dropCollection("group_test_collection"); - } - - @Test - public void singleKeyCreation() { - - Document gc = new GroupBy("a").getGroupByObject(); - - assertThat(gc).isEqualTo(Document.parse("{ \"key\" : { \"a\" : 1} , \"$reduce\" : null , \"initial\" : null }")); - } - - @Test - public void multipleKeyCreation() { - - Document gc = GroupBy.key("a", "b").getGroupByObject(); - - assertThat(gc).isEqualTo( - Document.parse("{ \"key\" : { \"a\" : 1 , \"b\" : 1} , \"$reduce\" : null , \"initial\" : null }")); - } - - @Test - public void keyFunctionCreation() { - - Document gc = GroupBy.keyFunction("classpath:keyFunction.js").getGroupByObject(); - - assertThat(gc).isEqualTo( - Document.parse("{ \"$keyf\" : \"classpath:keyFunction.js\" , \"$reduce\" : null , \"initial\" : null }")); - } - - @Test - public void simpleGroupFunction() { - - createGroupByData(); - GroupByResults results = mongoTemplate.group(GROUP_TEST_COLLECTION, GroupBy.key("x") - .initialDocument(new Document("count", 0)).reduceFunction("function(doc, prev) { prev.count += 1 }"), - XObject.class); - - assertMapReduceResults(results); - } - - @Test - public void simpleGroupWithKeyFunction() { - - createGroupByData(); - GroupByResults results = mongoTemplate - .group( - GROUP_TEST_COLLECTION, GroupBy.keyFunction("function(doc) { return { x : doc.x }; }") - .initialDocument("{ count: 0 }").reduceFunction("function(doc, prev) { prev.count += 1 }"), - XObject.class); - - assertMapReduceResults(results); - } - - @Test - public void simpleGroupWithFunctionsAsResources() { - - createGroupByData(); - GroupByResults results = mongoTemplate.group(GROUP_TEST_COLLECTION, - GroupBy.keyFunction("classpath:keyFunction.js").initialDocument("{ count: 0 }") - .reduceFunction("classpath:groupReduce.js"), - XObject.class); - - assertMapReduceResults(results); - } - - @Test - public void simpleGroupWithQueryAndFunctionsAsResources() { - - createGroupByData(); - GroupByResults results = mongoTemplate.group(where("x").gt(0), GROUP_TEST_COLLECTION, - keyFunction("classpath:keyFunction.js").initialDocument("{ count: 0 }") - .reduceFunction("classpath:groupReduce.js"), - XObject.class); - - assertMapReduceResults(results); - } - - private void assertMapReduceResults(GroupByResults results) { - - int numResults = 0; - for (XObject xObject : results) { - if (xObject.getX() == 1) { - assertThat(xObject.getCount()).isCloseTo(2, offset(0.001f)); - } - if (xObject.getX() == 2) { - assertThat(xObject.getCount()).isCloseTo(1, offset(0.001f)); - } - if (xObject.getX() == 3) { - assertThat(xObject.getCount()).isCloseTo(3, offset(0.001f)); - } - numResults++; - } - assertThat(numResults).isEqualTo(3); - assertThat(results.getKeys()).isEqualTo(3); - assertThat(results.getCount()).isCloseTo(6, offset(0.001)); - } - - private void createGroupByData() { - - MongoCollection c = mongoTemplate.getDb().getCollection(GROUP_TEST_COLLECTION, Document.class); - - c.insertOne(new Document("x", 1)); - c.insertOne(new Document("x", 1)); - c.insertOne(new Document("x", 2)); - c.insertOne(new Document("x", 3)); - c.insertOne(new Document("x", 3)); - c.insertOne(new Document("x", 3)); - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTests.java index 5672ee2d6..261e9d0fb 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapreduce/MapReduceTests.java @@ -76,7 +76,7 @@ public class MapReduceTests { template.dropCollection("jmr1_out"); template.dropCollection("jmr1"); template.dropCollection("jmrWithGeo"); - template.getMongoDbFactory().getMongoDatabase("jmr1-out-db").drop(); + template.getMongoDatabaseFactory().getMongoDatabase("jmr1-out-db").drop(); } @Test // DATAMONGO-260 @@ -155,7 +155,7 @@ public class MapReduceTests { options().outputDatabase("jmr1-out-db").outputCollection("jmr1-out"), ValueObject.class); assertThat( - template.getMongoDbFactory().getMongoDatabase("jmr1-out-db").listCollectionNames().into(new ArrayList<>())) + template.getMongoDatabaseFactory().getMongoDatabase("jmr1-out-db").listCollectionNames().into(new ArrayList<>())) .contains("jmr1-out"); } @@ -175,7 +175,7 @@ public class MapReduceTests { String mapWithExcludeFunction = "function(){ for ( var i=0; i results = mongoTemplate.mapReduce("jmr1", mapWithExcludeFunction, REDUCE_FUNCTION, - new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(), ValueObject.class); + new MapReduceOptions().scopeVariables(scopeVariables), ValueObject.class); assertThat(copyToMap(results)) // .hasSize(3) // diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/messaging/DefaultMessageListenerContainerTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/messaging/DefaultMessageListenerContainerTests.java index c47918c56..06f596f6c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/messaging/DefaultMessageListenerContainerTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/messaging/DefaultMessageListenerContainerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -72,7 +72,7 @@ public class DefaultMessageListenerContainerTests { @Template(database = DATABASE_NAME, initialEntitySet = Person.class) // static MongoTemplate template; - MongoDatabaseFactory dbFactory = template.getMongoDbFactory(); + MongoDatabaseFactory dbFactory = template.getMongoDatabaseFactory(); MongoCollection collection = template.getCollection(COLLECTION_NAME); MongoCollection collection2 = template.getCollection(COLLECTION_2_NAME); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java index 0eab98cb0..d4638ebd1 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/NearQueryUnitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2021 the original author or authors. + * Copyright 2011-2022 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. @@ -21,7 +21,6 @@ import java.math.BigDecimal; import java.math.RoundingMode; import org.junit.jupiter.api.Test; - import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.geo.Distance; @@ -140,7 +139,7 @@ public class NearQueryUnitTests { long num = 100; NearQuery query = NearQuery.near(new Point(1, 2)); - query.num(num); + query.limit(num); query.query(Query.query(Criteria.where("foo").is("bar"))); assertThat(DocumentTestUtils.getTypedValue(query.toDocument(), "num", Long.class)).isEqualTo(num); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/UpdateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/UpdateTests.java index 4902c5c23..636c15bee 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/UpdateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/UpdateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -90,30 +90,6 @@ public class UpdateTests { assertThat(u.getUpdateObject()).isEqualTo(Document.parse("{ \"$push\" : { \"authors\" : { \"name\" : \"Sven\"}}}")); } - @Test - public void testPushAll() { - - Map m1 = Collections.singletonMap("name", "Sven"); - Map m2 = Collections.singletonMap("name", "Maria"); - - Update u = new Update().pushAll("authors", new Object[] { m1, m2 }); - assertThat(u.getUpdateObject()).isEqualTo( - Document.parse("{ \"$pushAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}]}}")); - } - - @Test // DATAMONGO-354 - public void testMultiplePushAllShouldBePossibleWhenUsingDifferentFields() { - - Map m1 = Collections.singletonMap("name", "Sven"); - Map m2 = Collections.singletonMap("name", "Maria"); - - Update u = new Update().pushAll("authors", new Object[] { m1, m2 }); - u.pushAll("books", new Object[] { "Spring in Action" }); - - assertThat(u.getUpdateObject()).isEqualTo(Document.parse( - "{ \"$pushAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}] , \"books\" : [ \"Spring in Action\"]}}")); - } - @Test public void testAddToSet() { @@ -245,8 +221,8 @@ public class UpdateTests { @Test // DATAMONGO-853 public void testAddingSingleFieldOperationThrowsExceptionWhenCalledWithNullKey() { - assertThatIllegalArgumentException() - .isThrownBy(() -> new Update().addFieldOperation("$op", null, "exprected to throw IllegalArgumentException.")); + assertThatIllegalArgumentException().isThrownBy( + () -> new Update().addMultiFieldOperation("$op", null, "exprected to throw IllegalArgumentException.")); } @Test // DATAMONGO-853 @@ -256,7 +232,6 @@ public class UpdateTests { @Test // DATAMONGO-953 public void testEquality() { - Update actualUpdate = new Update() // .inc("size", 1) // .set("nl", null) // diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/Person.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/Person.java index a74ecc0e4..dd2c3ea50 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/Person.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/Person.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -48,7 +48,7 @@ public class Person extends Contact { private String firstname; private String lastname; - @Indexed(unique = true, dropDups = true) private String email; + @Indexed(unique = true) private String email; private Integer age; @SuppressWarnings("unused") private Sex sex; Date createdAt; @@ -75,8 +75,7 @@ public class Person extends Contact { @Unwrapped.Nullable(prefix = "u") // User unwrappedUser; - @DocumentReference - User spiritAnimal; + @DocumentReference User spiritAnimal; public Person() { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryTests.java index f5e14fdf7..6d296de5f 100755 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2021 the original author or authors. + * Copyright 2010-2022 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. @@ -30,7 +30,6 @@ import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; - import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; @@ -413,7 +412,7 @@ class SimpleMongoRepositoryTests { @EnableIfMongoServerVersion(isGreaterThanEqual = "4.0") void countShouldBePossibleInTransaction() { - MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDbFactory()); + MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDatabaseFactory()); TransactionTemplate tt = new TransactionTemplate(txmgr); tt.afterPropertiesSet(); @@ -437,7 +436,7 @@ class SimpleMongoRepositoryTests { @EnableIfMongoServerVersion(isGreaterThanEqual = "4.0") void existsShouldBePossibleInTransaction() { - MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDbFactory()); + MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDatabaseFactory()); TransactionTemplate tt = new TransactionTemplate(txmgr); tt.afterPropertiesSet(); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryVersionedEntityTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryVersionedEntityTests.java index 190310785..e9b82690e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryVersionedEntityTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepositoryVersionedEntityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2019-2021 the original author or authors. + * Copyright 2019-2022 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. @@ -27,7 +27,6 @@ import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.dao.OptimisticLockingFailureException; @@ -174,7 +173,7 @@ public class SimpleMongoRepositoryVersionedEntityTests { TransactionTemplate initTxTemplate() { - MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDbFactory()); + MongoTransactionManager txmgr = new MongoTransactionManager(template.getMongoDatabaseFactory()); TransactionTemplate tt = new TransactionTemplate(txmgr); tt.afterPropertiesSet(); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplate.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplate.java index c612319e5..88064d93c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplate.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -22,6 +22,7 @@ import java.util.stream.Collectors; import org.bson.Document; import org.springframework.context.ApplicationContext; +import org.springframework.data.mapping.callback.EntityCallbacks; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.mongodb.core.MongoTemplate; @@ -76,6 +77,10 @@ public class MongoTestTemplate extends MongoTemplate { super(config.databaseFactory(), config.mongoConverter()); ApplicationContext applicationContext = config.getApplicationContext(); + EntityCallbacks callbacks = config.getEntityCallbacks(); + if (callbacks != null) { + setEntityCallbacks(callbacks); + } if (applicationContext != null) { setApplicationContext(applicationContext); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplateConfiguration.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplateConfiguration.java index b50ff8813..9fa56c455 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplateConfiguration.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/test/util/MongoTestTemplateConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2021 the original author or authors. + * Copyright 2020-2022 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. @@ -16,15 +16,17 @@ package org.springframework.data.mongodb.test.util; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.ObjectFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.data.auditing.IsNewAwareAuditingHandler; +import org.springframework.data.mapping.callback.EntityCallbacks; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory; @@ -33,9 +35,8 @@ import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory; 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.convert.MongoCustomConversions; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; -import org.springframework.data.mongodb.core.mapping.event.AuditingEventListener; +import org.springframework.data.mongodb.core.mapping.event.AuditingEntityCallback; import org.springframework.data.mongodb.core.mapping.event.MongoMappingEvent; import org.springframework.lang.Nullable; @@ -69,19 +70,40 @@ public class MongoTestTemplateConfiguration { if (mongoConverterConfigurer.customConversions != null) { converter.setCustomConversions(mongoConverterConfigurer.customConversions); } + if (auditingConfigurer.hasAuditingHandler()) { + converter.setEntityCallbacks(getEntityCallbacks()); + } converter.afterPropertiesSet(); } return converter; } - List> getApplicationEventListener() { + EntityCallbacks getEntityCallbacks() { - ArrayList> listeners = new ArrayList<>(applicationContextConfigurer.listeners); - if (auditingConfigurer.hasAuditingHandler()) { - listeners.add(new AuditingEventListener(() -> auditingConfigurer.auditingHandlers(mappingContext()))); + EntityCallbacks callbacks = null; + if (getApplicationContext() != null) { + callbacks = EntityCallbacks.create(getApplicationContext()); } - return listeners; + if (!auditingConfigurer.hasAuditingHandler()) { + return callbacks; + } + if (callbacks == null) { + callbacks = EntityCallbacks.create(); + } + + callbacks.addEntityCallback(new AuditingEntityCallback(new ObjectFactory() { + @Override + public IsNewAwareAuditingHandler getObject() throws BeansException { + return auditingConfigurer.auditingHandlerFunction.apply(converter.getMappingContext()); + } + })); + return callbacks; + + } + + List> getApplicationEventListener() { + return new ArrayList<>(applicationContextConfigurer.listeners); } @Nullable @@ -110,7 +132,8 @@ public class MongoTestTemplateConfiguration { MongoMappingContext mappingContext() { if (mappingContext == null) { - mappingContext = new MongoTestMappingContext(mappingContextConfigurer).customConversions(mongoConverterConfigurer).init(); + mappingContext = new MongoTestMappingContext(mappingContextConfigurer).customConversions(mongoConverterConfigurer) + .init(); } return mappingContext; diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensionsTests.kt index 6e09b3773..8752ca281 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableAggregationOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -28,14 +28,6 @@ class ExecutableAggregationOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `aggregateAndReturn(KClass) extension should call its Java counterpart`() { - - operation.aggregateAndReturn(First::class) - verify { operation.aggregateAndReturn(First::class.java) } - } - @Test // DATAMONGO-1689 fun `aggregateAndReturn() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensionsTests.kt index c708f3e6e..b6d19f11a 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableFindOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -37,14 +37,6 @@ class ExecutableFindOperationExtensionsTests { val executableFind = mockk>(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `ExecutableFindOperation#query(KClass) extension should call its Java counterpart`() { - - operation.query(First::class) - verify { operation.query(First::class.java) } - } - @Test // DATAMONGO-1689 fun `ExecutableFindOperation#query() with reified type parameter extension should call its Java counterpart`() { @@ -52,14 +44,6 @@ class ExecutableFindOperationExtensionsTests { verify { operation.query(First::class.java) } } - @Test // DATAMONGO-1689, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ExecutableFindOperation#FindOperationWithProjection#asType(KClass) extension should call its Java counterpart`() { - - operationWithProjection.asType(User::class) - verify { operationWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-1689, DATAMONGO-2086 fun `ExecutableFindOperation#FindOperationWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { @@ -67,14 +51,6 @@ class ExecutableFindOperationExtensionsTests { verify { operationWithProjection.`as`(User::class.java) } } - @Test // DATAMONGO-1761, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ExecutableFindOperation#DistinctWithProjection#asType(KClass) extension should call its Java counterpart`() { - - distinctWithProjection.asType(User::class) - verify { distinctWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-2086 fun `ExecutableFindOperation#DistinctWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensionsTests.kt index f10e8ee18..5250c70b4 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableInsertOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -28,14 +28,6 @@ class ExecutableInsertOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `insert(KClass) extension should call its Java counterpart`() { - - operation.insert(First::class) - verify { operation.insert(First::class.java) } - } - @Test // DATAMONGO-1689 fun `insert() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensionsTests.kt index 76fdde331..5b71826e7 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableMapReduceOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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. @@ -30,14 +30,6 @@ class ExecutableMapReduceOperationExtensionsTests { val operationWithProjection = mockk>(relaxed = true) - @Test // DATAMONGO-1929 - @Suppress("DEPRECATION") - fun `ExecutableMapReduceOperation#mapReduce(KClass) extension should call its Java counterpart`() { - - operation.mapReduce(First::class) - verify { operation.mapReduce(First::class.java) } - } - @Test // DATAMONGO-1929 fun `ExecutableMapReduceOperation#mapReduce() with reified type parameter extension should call its Java counterpart`() { @@ -45,14 +37,6 @@ class ExecutableMapReduceOperationExtensionsTests { verify { operation.mapReduce(First::class.java) } } - @Test // DATAMONGO-1929, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ExecutableMapReduceOperation#MapReduceWithProjection#asType(KClass) extension should call its Java counterpart`() { - - operationWithProjection.asType(User::class) - verify { operationWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-1929, DATAMONGO-2086 fun `ExecutableMapReduceOperation#MapReduceWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensionsTests.kt index 235b9a856..e53b11527 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableRemoveOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -28,14 +28,6 @@ class ExecutableRemoveOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `remove(KClass) extension should call its Java counterpart`() { - - operation.remove(First::class) - verify { operation.remove(First::class.java) } - } - @Test // DATAMONGO-1689 fun `remove() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensionsTests.kt index f7e74ae31..fb7ec3f26 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ExecutableUpdateOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -30,14 +30,6 @@ class ExecutableUpdateOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `update(KClass) extension should call its Java counterpart`() { - - operation.update(First::class) - verify { operation.update(First::class.java) } - } - @Test // DATAMONGO-1719 fun `update() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensionsTests.kt index 7e8eb71c2..27cd1c9ec 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/MongoOperationsExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -23,8 +23,6 @@ import org.junit.Test import org.springframework.data.mongodb.core.BulkOperations.BulkMode import org.springframework.data.mongodb.core.aggregation.Aggregation import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions -import org.springframework.data.mongodb.core.query.Criteria -import org.springframework.data.mongodb.core.query.NearQuery import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update @@ -37,14 +35,6 @@ class MongoOperationsExtensionsTests { val operations = mockk(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `getCollectionName(KClass) extension should call its Java counterpart`() { - - operations.getCollectionName(First::class) - verify { operations.getCollectionName(First::class.java) } - } - @Test // DATAMONGO-1689 fun `getCollectionName() with reified type parameter extension should call its Java counterpart`() { @@ -77,23 +67,6 @@ class MongoOperationsExtensionsTests { verify { operations.stream(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `createCollection(KClass) extension should call its Java counterpart`() { - - operations.createCollection(First::class) - verify { operations.createCollection(First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `createCollection(KClass, CollectionOptions) extension should call its Java counterpart`() { - - val collectionOptions = mockk() - operations.createCollection(First::class, collectionOptions) - verify { operations.createCollection(First::class.java, collectionOptions) } - } - @Test // DATAMONGO-1689 fun `createCollection() with reified type parameter extension should call its Java counterpart`() { @@ -109,15 +82,6 @@ class MongoOperationsExtensionsTests { verify { operations.createCollection(First::class.java, collectionOptions) } } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `collectionExists(KClass) extension should call its Java counterpart`() { - - operations.collectionExists(First::class) - verify { operations.collectionExists(First::class.java) } - } - @Test // DATAMONGO-1689 fun `collectionExists() with reified type parameter extension should call its Java counterpart`() { @@ -125,14 +89,6 @@ class MongoOperationsExtensionsTests { verify { operations.collectionExists(First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `dropCollection(KClass) extension should call its Java counterpart`() { - - operations.dropCollection(First::class) - verify { operations.dropCollection(First::class.java) } - } - @Test // DATAMONGO-1689 fun `dropCollection() with reified type parameter extension should call its Java counterpart`() { @@ -140,14 +96,6 @@ class MongoOperationsExtensionsTests { verify { operations.dropCollection(First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `indexOps(KClass) extension should call its Java counterpart`() { - - operations.indexOps(First::class) - verify { operations.indexOps(First::class.java) } - } - @Test // DATAMONGO-1689 fun `indexOps() with reified type parameter extension should call its Java counterpart`() { @@ -155,27 +103,6 @@ class MongoOperationsExtensionsTests { verify { operations.indexOps(First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `bulkOps(BulkMode, KClass) extension should call its Java counterpart`() { - - val bulkMode = BulkMode.ORDERED - - operations.bulkOps(bulkMode, First::class) - verify { operations.bulkOps(bulkMode, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `bulkOps(BulkMode, KClass, String) extension should call its Java counterpart`() { - - val bulkMode = BulkMode.ORDERED - val collectionName = "foo" - - operations.bulkOps(bulkMode, First::class, collectionName) - verify { operations.bulkOps(bulkMode, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `bulkOps(BulkMode) with reified type parameter extension should call its Java counterpart`() { @@ -211,45 +138,6 @@ class MongoOperationsExtensionsTests { verify { operations.findAll(First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `group(String, GroupBy) with reified type parameter extension should call its Java counterpart`() { - - val collectionName = "foo" - val groupBy = mockk() - - operations.group(collectionName, groupBy) - verify { operations.group(collectionName, groupBy, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `group(Criteria, String, GroupBy) with reified type parameter extension should call its Java counterpart`() { - - val criteria = mockk() - val collectionName = "foo" - val groupBy = mockk() - - operations.group(criteria, collectionName, groupBy) - verify { operations.group(criteria, collectionName, groupBy, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `aggregate(Aggregation, KClass) with reified type parameter extension should call its Java counterpart`() { - - val aggregation = mockk() - - operations.aggregate(aggregation, Second::class) - verify { - operations.aggregate( - aggregation, - Second::class.java, - First::class.java - ) - } - } - @Test // #3508 fun `aggregate(Aggregation) with reified type parameter extension should call its Java counterpart`() { @@ -275,22 +163,6 @@ class MongoOperationsExtensionsTests { verify { operations.aggregate(aggregation, collectionName, First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `aggregateStream(Aggregation, KClass) with reified type parameter extension should call its Java counterpart`() { - - val aggregation = mockk() - - operations.aggregateStream(aggregation, Second::class) - verify { - operations.aggregateStream( - aggregation, - Second::class.java, - First::class.java - ) - } - } - @Test // #3508 fun `aggregateStream(Aggregation) with reified type parameter extension should call its Java counterpart`() { @@ -370,27 +242,6 @@ class MongoOperationsExtensionsTests { verify { operations.mapReduce(query, collectionName, mapFunction, reduceFunction, options, First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `geoNear(Query) with reified type parameter extension should call its Java counterpart`() { - - val query = NearQuery.near(0.0, 0.0) - - operations.geoNear(query) - verify { operations.geoNear(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `geoNear(Query, String) with reified type parameter extension should call its Java counterpart`() { - - val collectionName = "foo" - val query = NearQuery.near(0.0, 0.0) - - operations.geoNear(query, collectionName) - verify { operations.geoNear(query, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `findOne(Query) with reified type parameter extension should call its Java counterpart`() { @@ -410,16 +261,6 @@ class MongoOperationsExtensionsTests { verify { operations.findOne(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `exists(Query, KClass) extension should call its Java counterpart`() { - - val query = mockk() - - operations.exists(query, First::class) - verify { operations.exists(query, First::class.java) } - } - @Test // DATAMONGO-1689 fun `exists(Query) with reified type parameter extension should call its Java counterpart`() { @@ -535,37 +376,6 @@ class MongoOperationsExtensionsTests { verify { operations.count(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `count(Query, KClass) with reified type parameter extension should call its Java counterpart`() { - - val query = mockk() - - operations.count(query, First::class) - verify { operations.count(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `count(Query, KClass, String) with reified type parameter extension should call its Java counterpart`() { - - val query = mockk() - val collectionName = "foo" - - operations.count(query, First::class, collectionName) - verify { operations.count(query, First::class.java, collectionName) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `insert(Collection, KClass) extension should call its Java counterpart`() { - - val collection = listOf(First(), First()) - - operations.insert(collection, First::class) - verify { operations.insert(collection, First::class.java) } - } - @Test // DATAMONGO-2208 fun `insert(Collection) with reified type parameter extension should call its Java counterpart`() { @@ -575,29 +385,6 @@ class MongoOperationsExtensionsTests { verify { operations.insert(collection, First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `upsert(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.upsert(query, update, First::class) - verify { operations.upsert(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `upsert(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.upsert(query, update, First::class, collectionName) - verify { operations.upsert(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `upsert(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -619,29 +406,6 @@ class MongoOperationsExtensionsTests { verify { operations.upsert(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateFirst(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.updateFirst(query, update, First::class) - verify { operations.updateFirst(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateFirst(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.updateFirst(query, update, First::class, collectionName) - verify { operations.updateFirst(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `updateFirst(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -663,29 +427,6 @@ class MongoOperationsExtensionsTests { verify { operations.updateFirst(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateMulti(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.updateMulti(query, update, First::class) - verify { operations.updateMulti(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateMulti(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.updateMulti(query, update, First::class, collectionName) - verify { operations.updateMulti(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `updateMulti(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -707,27 +448,6 @@ class MongoOperationsExtensionsTests { verify { operations.updateMulti(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `remove(Query, KClass) extension should call its Java counterpart`() { - - val query = mockk() - - operations.remove(query, First::class) - verify { operations.remove(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `remove(Query, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val collectionName = "foo" - - operations.remove(query, First::class, collectionName) - verify { operations.remove(query, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `remove(Query) with reified type parameter extension should call its Java counterpart`() { @@ -756,34 +476,6 @@ class MongoOperationsExtensionsTests { verify { operations.findAllAndRemove(query, First::class.java) } } - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(String, KClass) should call java counterpart`() { - - operations.findDistinct("field", First::class) - verify { operations.findDistinct("field", First::class.java, String::class.java) } - } - - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", First::class) - verify { operations.findDistinct(query, "field", First::class.java, String::class.java) } - } - - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", "collection", First::class) - verify { operations.findDistinct(query, "field", "collection", First::class.java, String::class.java) } - } - @Test // DATAMONGO-1761 fun `findDistinctImplicit(Query, String) should call java counterpart`() { @@ -801,14 +493,4 @@ class MongoOperationsExtensionsTests { operations.findDistinct(query, "field", "collection") verify { operations.findDistinct(query, "field", "collection", First::class.java, String::class.java) } } - - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", First::class) - verify { operations.findDistinct(query, "field", First::class.java, String::class.java) } - } } diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensionsTests.kt index 0bc661460..c05312968 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveAggregationOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -33,14 +33,6 @@ class ReactiveAggregationOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `aggregateAndReturn(KClass) extension should call its Java counterpart`() { - - operation.aggregateAndReturn(First::class) - verify { operation.aggregateAndReturn(First::class.java) } - } - @Test // DATAMONGO-1719 fun `aggregateAndReturn() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensionsTests.kt index 722229bab..f7c44e038 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveFindOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -46,14 +46,6 @@ class ReactiveFindOperationExtensionsTests { val reactiveFind = mockk>(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `ReactiveFind#query(KClass) extension should call its Java counterpart`() { - - operation.query(First::class) - verify { operation.query(First::class.java) } - } - @Test // DATAMONGO-1719 fun `ReactiveFind#query() with reified type parameter extension should call its Java counterpart`() { @@ -61,14 +53,6 @@ class ReactiveFindOperationExtensionsTests { verify { operation.query(First::class.java) } } - @Test // DATAMONGO-1719, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ReactiveFind#FindOperatorWithProjection#asType(KClass) extension should call its Java counterpart`() { - - operationWithProjection.asType(User::class) - verify { operationWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-1719, DATAMONGO-2086 fun `ReactiveFind#FindOperatorWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { @@ -76,14 +60,6 @@ class ReactiveFindOperationExtensionsTests { verify { operationWithProjection.`as`(User::class.java) } } - @Test // DATAMONGO-1761, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ReactiveFind#DistinctWithProjection#asType(KClass) extension should call its Java counterpart`() { - - distinctWithProjection.asType(User::class) - verify { distinctWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-2086 fun `ReactiveFind#DistinctWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensionsTests.kt index abc1eb42f..57d8552a4 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveInsertOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -34,14 +34,6 @@ class ReactiveInsertOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `insert(KClass) extension should call its Java counterpart`() { - - operation.insert(First::class) - verify { operation.insert(First::class.java) } - } - @Test // DATAMONGO-1719 fun `insert() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensionsTests.kt index fa74c458c..568002fb1 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMapReduceOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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,14 +35,6 @@ class ReactiveMapReduceOperationExtensionsTests { val operationWithProjection = mockk>(relaxed = true) - @Test // DATAMONGO-1929 - @Suppress("DEPRECATION") - fun `ReactiveMapReduceOperation#mapReduce(KClass) extension should call its Java counterpart`() { - - operation.mapReduce(First::class) - verify { operation.mapReduce(First::class.java) } - } - @Test // DATAMONGO-1929 fun `ReactiveMapReduceOperation#mapReduce() with reified type parameter extension should call its Java counterpart`() { @@ -50,14 +42,6 @@ class ReactiveMapReduceOperationExtensionsTests { verify { operation.mapReduce(First::class.java) } } - @Test // DATAMONGO-1929, DATAMONGO-2086 - @Suppress("DEPRECATION") - fun `ReactiveMapReduceOperation#MapReduceWithProjection#asType(KClass) extension should call its Java counterpart`() { - - operationWithProjection.asType(User::class) - verify { operationWithProjection.`as`(User::class.java) } - } - @Test // DATAMONGO-1929, DATAMONGO-2086 fun `ReactiveMapReduceOperation#MapReduceWithProjection#asType() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensionsTests.kt index 7ad29572b..28b75570b 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveMongoOperationsExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -36,14 +36,6 @@ class ReactiveMongoOperationsExtensionsTests { val operations = mockk(relaxed = true) - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `indexOps(KClass) extension should call its Java counterpart`() { - - operations.indexOps(First::class) - verify { operations.indexOps(First::class.java) } - } - @Test // DATAMONGO-1689 fun `indexOps() with reified type parameter extension should call its Java counterpart`() { @@ -60,24 +52,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.execute(First::class.java, collectionCallback) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `createCollection(KClass) extension should call its Java counterpart`() { - - operations.createCollection(First::class) - verify { operations.createCollection(First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `createCollection(KClass, CollectionOptions) extension should call its Java counterpart`() { - - val collectionOptions = mockk() - - operations.createCollection(First::class, collectionOptions) - verify { operations.createCollection(First::class.java, collectionOptions) } - } - @Test // DATAMONGO-1689 fun `createCollection() with reified type parameter extension should call its Java counterpart`() { @@ -94,14 +68,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.createCollection(First::class.java, collectionOptions) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `collectionExists(KClass) extension should call its Java counterpart`() { - - operations.collectionExists(First::class) - verify { operations.collectionExists(First::class.java) } - } - @Test // DATAMONGO-1689 fun `collectionExists() with reified type parameter extension should call its Java counterpart`() { @@ -109,14 +75,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.collectionExists(First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `dropCollection(KClass) extension should call its Java counterpart`() { - - operations.dropCollection(First::class) - verify { operations.dropCollection(First::class.java) } - } - @Test // DATAMONGO-1689 fun `dropCollection() with reified type parameter extension should call its Java counterpart`() { @@ -159,16 +117,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.findOne(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `exists(Query, KClass) extension should call its Java counterpart`() { - - val query = mockk() - - operations.exists(query, First::class) - verify { operations.exists(query, First::class.java) } - } - @Test // DATAMONGO-1689 fun `exists(Query) with reified type parameter extension should call its Java counterpart`() { @@ -216,27 +164,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.findById(id, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `geoNear(Query) with reified type parameter extension should call its Java counterpart`() { - - val query = NearQuery.near(0.0, 0.0) - - operations.geoNear(query) - verify { operations.geoNear(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `geoNear(Query, String) with reified type parameter extension should call its Java counterpart`() { - - val collectionName = "foo" - val query = NearQuery.near(0.0, 0.0) - - operations.geoNear(query, collectionName) - verify { operations.geoNear(query, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `findAndModify(Query, Update, FindAndModifyOptions) with reified type parameter extension should call its Java counterpart`() { @@ -305,37 +232,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.count(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `count(Query, KClass) with reified type parameter extension should call its Java counterpart`() { - - val query = mockk() - - operations.count(query, First::class) - verify { operations.count(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `count(Query, KClass, String) with reified type parameter extension should call its Java counterpart`() { - - val query = mockk() - val collectionName = "foo" - - operations.count(query, First::class, collectionName) - verify { operations.count(query, First::class.java, collectionName) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `insert(Collection, KClass) extension should call its Java counterpart`() { - - val collection = listOf(First(), First()) - - operations.insert(collection, First::class) - verify { operations.insert(collection, First::class.java) } - } - @Test // DATAMONGO-2208 fun `insert(Collection) with reified type parameter extension should call its Java counterpart`() { @@ -345,39 +241,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.insert(collection, First::class.java) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `insertAll(Mono, KClass) extension should call its Java counterpart`() { - - val collection = Mono.just(listOf(First(), First())) - - operations.insertAll(collection, First::class) - verify { operations.insertAll(collection, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `upsert(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.upsert(query, update, First::class) - verify { operations.upsert(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `upsert(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.upsert(query, update, First::class, collectionName) - verify { operations.upsert(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `upsert(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -399,29 +262,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.upsert(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateFirst(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.updateFirst(query, update, First::class) - verify { operations.updateFirst(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateFirst(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.updateFirst(query, update, First::class, collectionName) - verify { operations.updateFirst(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `updateFirst(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -443,29 +283,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.updateFirst(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateMulti(Query, Update, KClass) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - - operations.updateMulti(query, update, First::class) - verify { operations.updateMulti(query, update, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `updateMulti(Query, Update, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val update = mockk() - val collectionName = "foo" - - operations.updateMulti(query, update, First::class, collectionName) - verify { operations.updateMulti(query, update, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `updateMulti(Query, Update) with reified type parameter extension should call its Java counterpart`() { @@ -487,27 +304,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.updateMulti(query, update, First::class.java, collectionName) } } - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `remove(Query, KClass) extension should call its Java counterpart`() { - - val query = mockk() - - operations.remove(query, First::class) - verify { operations.remove(query, First::class.java) } - } - - @Test // DATAMONGO-1689 - @Suppress("DEPRECATION") - fun `remove(Query, KClass, String) extension should call its Java counterpart`() { - - val query = mockk() - val collectionName = "foo" - - operations.remove(query, First::class, collectionName) - verify { operations.remove(query, First::class.java, collectionName) } - } - @Test // DATAMONGO-1689 fun `remove(Query) with reified type parameter extension should call its Java counterpart`() { @@ -555,34 +351,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.tail(query, First::class.java, collectionName) } } - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(String, KClass) should call java counterpart`() { - - operations.findDistinct("field", First::class) - verify { operations.findDistinct("field", First::class.java, String::class.java) } - } - - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", First::class) - verify { operations.findDistinct(query, "field", First::class.java, String::class.java) } - } - - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", "collection", First::class) - verify { operations.findDistinct(query, "field", "collection", First::class.java, String::class.java) } - } - @Test // DATAMONGO-1761 fun `findDistinctImplicit(Query, String) should call java counterpart`() { @@ -601,23 +369,6 @@ class ReactiveMongoOperationsExtensionsTests { verify { operations.findDistinct(query, "field", "collection", First::class.java, String::class.java) } } - @Test // DATAMONGO-1761 - @Suppress("DEPRECATION") - fun `findDistinct(Query, String, KClass) should call java counterpart`() { - - val query = mockk() - - operations.findDistinct(query, "field", First::class) - verify { - operations.findDistinct( - query, - "field", - First::class.java, - String::class.java - ) - } - } - @Test // #893 fun `aggregate(TypedAggregation, String, KClass) should call java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensionsTests.kt index e637dd94e..a19aef6ed 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveRemoveOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,14 +35,6 @@ class ReactiveRemoveOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `remove(KClass) extension should call its Java counterpart`() { - - operation.remove(First::class) - verify { operation.remove(First::class.java) } - } - @Test // DATAMONGO-1719 fun `remove() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensionsTests.kt index 16eccc5b6..eba6aa8b7 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/ReactiveUpdateOperationExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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. @@ -36,14 +36,6 @@ class ReactiveUpdateOperationExtensionsTests { val operation = mockk(relaxed = true) - @Test // DATAMONGO-1719 - @Suppress("DEPRECATION") - fun `update(KClass) extension should call its Java counterpart`() { - - operation.update(First::class) - verify { operation.update(First::class.java) } - } - @Test // DATAMONGO-1719 fun `update() with reified type parameter extension should call its Java counterpart`() { diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensionsTests.kt index 02753f16d..81916ab67 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/CriteriaExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2017-2021 the original author or authors. + * Copyright 2017-2022 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,7 @@ import io.mockk.mockk import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.Test +import org.springframework.data.mapping.div /** * @author Sebastien Deleuze diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathTests.kt deleted file mode 100644 index 17347d815..000000000 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/KPropertyPathTests.kt +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2018-2021 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 - * - * https://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.query - -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test - -/** - * Unit tests for [KPropertyPath] and its extensions. - * - * @author Tjeu Kayim - * @author Yoann de Martino - * @author Mark Paluch - */ -class KPropertyPathTests { - - @Test - fun `Convert normal KProperty to field name`() { - - val property = asString(Book::title) - - assertThat(property).isEqualTo("title") - } - - @Test - fun `Convert nested KProperty to field name`() { - - val property = asString(Book::author / Author::name) - - assertThat(property).isEqualTo("author.name") - } - - @Test - fun `Convert double nested KProperty to field name`() { - - class Entity(val book: Book) - - val property = asString(Entity::book / Book::author / Author::name) - - assertThat(property).isEqualTo("book.author.name") - } - - @Test - fun `Convert triple nested KProperty to field name`() { - - class Entity(val book: Book) - class AnotherEntity(val entity: Entity) - - val property = asString(AnotherEntity::entity / Entity::book / Book::author / Author::name) - - assertThat(property).isEqualTo("entity.book.author.name") - } - - @Test - fun `Convert simple KProperty to property path using toPath`() { - - class AnotherEntity(val entity: String) - - val property = (AnotherEntity::entity).toPath() - - assertThat(property).isEqualTo("entity") - } - - @Test - fun `Convert nested KProperty to field name using toPath()`() { - - val property = (Book::author / Author::name).toPath() - - assertThat(property).isEqualTo("author.name") - } - - @Test - fun `Convert triple nested KProperty to property path using toPath`() { - - class Entity(val book: Book) - class AnotherEntity(val entity: Entity) - - val property = (AnotherEntity::entity / Entity::book / Book::author / Author::name).toPath() - - assertThat(property).isEqualTo("entity.book.author.name") - } - - @Test // DATAMONGO-2661 - fun `Convert nullable KProperty to field name`() { - class Cat(val name: String) - class Owner(val cat: Cat?) - - val property = asString(Owner::cat / Cat::name) - assertThat(property).isEqualTo("cat.name") - } - - class Book(val title: String, val author: Author) - class Author(val name: String) -} diff --git a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensionsTests.kt b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensionsTests.kt index 7a5c358fa..5cee07d7e 100644 --- a/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensionsTests.kt +++ b/spring-data-mongodb/src/test/kotlin/org/springframework/data/mongodb/core/query/TypedCriteriaExtensionsTests.kt @@ -1,5 +1,5 @@ /* - * Copyright 2018-2021 the original author or authors. + * Copyright 2018-2022 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 org.bson.BsonRegularExpression import org.junit.Test import org.springframework.data.geo.Circle import org.springframework.data.geo.Point +import org.springframework.data.mapping.div import org.springframework.data.mongodb.core.geo.GeoJsonPoint import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type import java.util.regex.Pattern