Search in sources :

Example 26 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class MongoTemplate method findDistinct.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.MongoOperations#findDistinct(org.springframework.data.mongodb.core.query.Query, java.lang.String, java.lang.String, java.lang.Class, java.lang.Class)
	 */
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass, Class<T> resultClass) {
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(field, "Field must not be null!");
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(entityClass, "EntityClass must not be null!");
    Assert.notNull(resultClass, "ResultClass must not be null!");
    MongoPersistentEntity<?> entity = entityClass != Object.class ? getPersistentEntity(entityClass) : null;
    DistinctQueryContext distinctQueryContext = queryOperations.distinctQueryContext(query, field);
    Document mappedQuery = distinctQueryContext.getMappedQuery(entity);
    String mappedFieldName = distinctQueryContext.getMappedFieldName(entity);
    Class<T> mongoDriverCompatibleType = distinctQueryContext.getDriverCompatibleClass(resultClass);
    MongoIterable<?> result = execute(collectionName, (collection) -> {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Executing findDistinct using query %s for field: %s in collection: %s", serializeToJsonSafely(mappedQuery), field, collectionName));
        }
        QueryCursorPreparer preparer = new QueryCursorPreparer(query, entityClass);
        if (preparer.hasReadPreference()) {
            collection = collection.withReadPreference(preparer.getReadPreference());
        }
        DistinctIterable<T> iterable = collection.distinct(mappedFieldName, mappedQuery, mongoDriverCompatibleType);
        distinctQueryContext.applyCollation(entityClass, iterable::collation);
        return iterable;
    });
    if (resultClass == Object.class || mongoDriverCompatibleType != resultClass) {
        MongoConverter converter = getConverter();
        DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        result = result.map((source) -> converter.mapValueToTargetType(source, distinctQueryContext.getMostSpecificConversionTargetType(resultClass, entityClass), dbRefResolver));
    }
    try {
        return (List<T>) result.into(new ArrayList<>());
    } catch (RuntimeException e) {
        throw potentiallyConvertRuntimeException(e, exceptionTranslator);
    }
}
Also used : Document(org.bson.Document) EntityCallbacks(org.springframework.data.mapping.callback.EntityCallbacks) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) NumberUtils(org.springframework.util.NumberUtils) BsonUtils(org.springframework.data.mongodb.util.BsonUtils) MongoDatabase(com.mongodb.client.MongoDatabase) BigDecimal(java.math.BigDecimal) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) BulkOperationContext(org.springframework.data.mongodb.core.DefaultBulkOperations.BulkOperationContext) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) MapReduceResults(org.springframework.data.mongodb.core.mapreduce.MapReduceResults) CursorOption(org.springframework.data.mongodb.core.query.Meta.CursorOption) MongoJsonSchemaMapper(org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper) Resource(org.springframework.core.io.Resource) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) AggregateIterable(com.mongodb.client.AggregateIterable) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) CollectionUtils(org.springframework.util.CollectionUtils) LogFactory(org.apache.commons.logging.LogFactory) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) ApplicationContextAware(org.springframework.context.ApplicationContextAware) MongoDatabaseUtils(org.springframework.data.mongodb.MongoDatabaseUtils) java.util(java.util) Validator(org.springframework.data.mongodb.core.validation.Validator) IndexOperationsProvider(org.springframework.data.mongodb.core.index.IndexOperationsProvider) MongoCollection(com.mongodb.client.MongoCollection) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) GroupByResults(org.springframework.data.mongodb.core.mapreduce.GroupByResults) MappingContext(org.springframework.data.mapping.context.MappingContext) UpdateDefinition(org.springframework.data.mongodb.core.query.UpdateDefinition) Bson(org.bson.conversions.Bson) DbRefResolver(org.springframework.data.mongodb.core.convert.DbRefResolver) MappingException(org.springframework.data.mapping.MappingException) Nullable(org.springframework.lang.Nullable) JsonSchemaMapper(org.springframework.data.mongodb.core.convert.JsonSchemaMapper) com.mongodb.client.model(com.mongodb.client.model) CountContext(org.springframework.data.mongodb.core.QueryOperations.CountContext) org.springframework.data.mongodb.core.mapping.event(org.springframework.data.mongodb.core.mapping.event) QueryMapper(org.springframework.data.mongodb.core.convert.QueryMapper) ObjectUtils(org.springframework.util.ObjectUtils) DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) TypedAggregation(org.springframework.data.mongodb.core.aggregation.TypedAggregation) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) MongoMappingEventPublisher(org.springframework.data.mongodb.core.index.MongoMappingEventPublisher) Criteria(org.springframework.data.mongodb.core.query.Criteria) ResourceUtils(org.springframework.util.ResourceUtils) DistinctIterable(com.mongodb.client.DistinctIterable) DefaultDbRefResolver(org.springframework.data.mongodb.core.convert.DefaultDbRefResolver) MongoIterable(com.mongodb.client.MongoIterable) CloseableIterator(org.springframework.data.util.CloseableIterator) Collation(org.springframework.data.mongodb.core.query.Collation) EntityProjection(org.springframework.data.projection.EntityProjection) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) MapReduceOptions(org.springframework.data.mongodb.core.mapreduce.MapReduceOptions) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) MapReduceIterable(com.mongodb.client.MapReduceIterable) AdaptibleEntity(org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity) MongoWriter(org.springframework.data.mongodb.core.convert.MongoWriter) RoundingMode(java.math.RoundingMode) Meta(org.springframework.data.mongodb.core.query.Meta) ResourceLoader(org.springframework.core.io.ResourceLoader) MongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) MongoException(com.mongodb.MongoException) ApplicationListener(org.springframework.context.ApplicationListener) AggregationResults(org.springframework.data.mongodb.core.aggregation.AggregationResults) Collectors(java.util.stream.Collectors) FindIterable(com.mongodb.client.FindIterable) UpdateMapper(org.springframework.data.mongodb.core.convert.UpdateMapper) TypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.TypeBasedAggregationOperationContext) UpdateContext(org.springframework.data.mongodb.core.QueryOperations.UpdateContext) Metric(org.springframework.data.geo.Metric) ReadPreference(com.mongodb.ReadPreference) DataAccessException(org.springframework.dao.DataAccessException) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) MongoClient(com.mongodb.client.MongoClient) BulkMode(org.springframework.data.mongodb.core.BulkOperations.BulkMode) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) Distance(org.springframework.data.geo.Distance) IndexOperations(org.springframework.data.mongodb.core.index.IndexOperations) EntityReader(org.springframework.data.convert.EntityReader) ArrayFilter(org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter) MongoCursor(com.mongodb.client.MongoCursor) Granularity(org.springframework.data.mongodb.core.timeseries.Granularity) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) AggregationDefinition(org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition) GroupBy(org.springframework.data.mongodb.core.mapreduce.GroupBy) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) TimeUnit(java.util.concurrent.TimeUnit) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) ClientSessionOptions(com.mongodb.ClientSessionOptions) GeoResults(org.springframework.data.geo.GeoResults) DeleteResult(com.mongodb.client.result.DeleteResult) Log(org.apache.commons.logging.Log) ClientSession(com.mongodb.client.ClientSession) GeoResult(org.springframework.data.geo.GeoResult) SessionSynchronization(org.springframework.data.mongodb.SessionSynchronization) WriteConcern(com.mongodb.WriteConcern) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) DefaultDbRefResolver(org.springframework.data.mongodb.core.convert.DefaultDbRefResolver) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter)

Example 27 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class MongoParametersParameterAccessorUnitTests method shouldDetectCollation.

// DATAMONGO-1854
@Test
public void shouldDetectCollation() throws NoSuchMethodException, SecurityException {
    Method method = PersonRepository.class.getMethod("findByFirstname", String.class, Collation.class);
    MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, factory, context);
    Collation collation = Collation.of("en_US");
    MongoParameterAccessor accessor = new MongoParametersParameterAccessor(queryMethod, new Object[] { "dalinar", collation });
    assertThat(accessor.getCollation()).isEqualTo(collation);
}
Also used : Method(java.lang.reflect.Method) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 28 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class SimpleMongoRepositoryUnitTests method shouldAddDefaultCollationToFindWithSortForExampleIfPresent.

// DATAMONGO-1854
@Test
public void shouldAddDefaultCollationToFindWithSortForExampleIfPresent() {
    Collation collation = Collation.of("en_US");
    when(entityInformation.getCollation()).thenReturn(collation);
    repository.findAll(Example.of(new TestDummy()), Sort.by("nothing"));
    ArgumentCaptor<Query> query = ArgumentCaptor.forClass(Query.class);
    verify(mongoOperations).find(query.capture(), any(), any());
    assertThat(query.getValue().getCollation()).contains(collation);
}
Also used : Query(org.springframework.data.mongodb.core.query.Query) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 29 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class SimpleMongoRepositoryUnitTests method shouldAddDefaultCollationToCountForExampleIfPresent.

// DATAMONGO-1854
@Test
public void shouldAddDefaultCollationToCountForExampleIfPresent() {
    Collation collation = Collation.of("en_US");
    when(entityInformation.getCollation()).thenReturn(collation);
    repository.count(Example.of(new TestDummy()));
    ArgumentCaptor<Query> query = ArgumentCaptor.forClass(Query.class);
    verify(mongoOperations).count(query.capture(), any(), any());
    assertThat(query.getValue().getCollation()).contains(collation);
}
Also used : Query(org.springframework.data.mongodb.core.query.Query) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Example 30 with Collation

use of org.springframework.data.mongodb.core.query.Collation in project spring-data-mongodb by spring-projects.

the class AbstractMongoQueryUnitTests method shouldApplyCollationParameter.

// DATAMONGO-1854
@Test
void shouldApplyCollationParameter() {
    Collation collation = Collation.of("en_US");
    // 
    createQueryForMethod("findWithCollationParameterByFirstName", String.class, Collation.class).execute(new Object[] { "dalinar", collation });
    ArgumentCaptor<Query> captor = ArgumentCaptor.forClass(Query.class);
    verify(withQueryMock).matching(captor.capture());
    assertThat(captor.getValue().getCollation()).contains(collation);
}
Also used : BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) FindWithQuery(org.springframework.data.mongodb.core.ExecutableFindOperation.FindWithQuery) UpdateWithQuery(org.springframework.data.mongodb.core.ExecutableUpdateOperation.UpdateWithQuery) Query(org.springframework.data.mongodb.core.query.Query) Collation(org.springframework.data.mongodb.core.query.Collation) Test(org.junit.jupiter.api.Test)

Aggregations

Collation (org.springframework.data.mongodb.core.query.Collation)33 Query (org.springframework.data.mongodb.core.query.Query)24 Test (org.junit.jupiter.api.Test)19 Document (org.bson.Document)15 Collectors (java.util.stream.Collectors)7 DataAccessException (org.springframework.dao.DataAccessException)7 BasicQuery (org.springframework.data.mongodb.core.query.BasicQuery)7 MongoException (com.mongodb.MongoException)6 WriteConcern (com.mongodb.WriteConcern)6 DeleteResult (com.mongodb.client.result.DeleteResult)6 UpdateResult (com.mongodb.client.result.UpdateResult)6 AggregationOptions (org.springframework.data.mongodb.core.aggregation.AggregationOptions)6 TypedAggregation (org.springframework.data.mongodb.core.aggregation.TypedAggregation)6 Criteria (org.springframework.data.mongodb.core.query.Criteria)5 MongoPersistentEntity (org.springframework.data.mongodb.core.mapping.MongoPersistentEntity)4 FullDocument (com.mongodb.client.model.changestream.FullDocument)3 java.util (java.util)3 Collection (java.util.Collection)3 Bson (org.bson.conversions.Bson)3 BeansException (org.springframework.beans.BeansException)3