Search in sources :

Example 1 with EntityProjection

use of org.springframework.data.projection.EntityProjection in project spring-data-mongodb by spring-projects.

the class MappingMongoConverterUnitTests method projectShouldReadNestedProjection.

// GH-2860
@Test
void projectShouldReadNestedProjection() {
    org.bson.Document source = new org.bson.Document("addresses", Collections.singletonList(new org.bson.Document("s", "hwy")));
    EntityProjectionIntrospector introspector = EntityProjectionIntrospector.create(converter.getProjectionFactory(), EntityProjectionIntrospector.ProjectionPredicate.typeHierarchy().and((target, underlyingType) -> !converter.conversions.isSimpleType(target)), mappingContext);
    EntityProjection<WithNestedProjection, Person> projection = introspector.introspect(WithNestedProjection.class, Person.class);
    WithNestedProjection person = converter.project(projection, source);
    assertThat(person.getAddresses()).extracting(AddressProjection::getStreet).hasSize(1).containsOnly("hwy");
}
Also used : EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) BeforeEach(org.junit.jupiter.api.BeforeEach) MappingInstantiationException(org.springframework.data.mapping.model.MappingInstantiationException) EntityCallbacks(org.springframework.data.mapping.callback.EntityCallbacks) ProjectingType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.ProjectingType) CustomConversions(org.springframework.data.convert.CustomConversions) Metrics(org.springframework.data.geo.Metrics) NestedType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.NestedType) URL(java.net.URL) EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Shape(org.springframework.data.geo.Shape) AfterConvertCallback(org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback) Unwrapped(org.springframework.data.mongodb.core.mapping.Unwrapped) Disabled(org.junit.jupiter.api.Disabled) Box(org.springframework.data.geo.Box) EntityProjection(org.springframework.data.projection.EntityProjection) BasicDBList(com.mongodb.BasicDBList) Document(org.springframework.data.mongodb.core.mapping.Document) BigDecimal(java.math.BigDecimal) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DBObject(com.mongodb.DBObject) Assertions(org.assertj.core.api.Assertions) BigInteger(java.math.BigInteger) Transient(org.springframework.data.annotation.Transient) Point(org.springframework.data.geo.Point) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) TypeAlias(org.springframework.data.annotation.TypeAlias) EqualsAndHashCode(lombok.EqualsAndHashCode) ZoneId(java.time.ZoneId) Test(org.junit.jupiter.api.Test) Code(org.bson.types.Code) NonNull(org.springframework.lang.NonNull) Id(org.springframework.data.annotation.Id) java.util(java.util) WritingConverter(org.springframework.data.convert.WritingConverter) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) Getter(lombok.Getter) PersistenceConstructor(org.springframework.data.annotation.PersistenceConstructor) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Mock(org.mockito.Mock) LocalDateTime(java.time.LocalDateTime) Distance(org.springframework.data.geo.Distance) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Value(org.springframework.beans.factory.annotation.Value) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) MappingException(org.springframework.data.mapping.MappingException) Sphere(org.springframework.data.mongodb.core.geo.Sphere) Nullable(org.springframework.lang.Nullable) TextScore(org.springframework.data.mongodb.core.mapping.TextScore) Decimal128(org.bson.types.Decimal128) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) Converter(org.springframework.core.convert.converter.Converter) Polygon(org.springframework.data.geo.Polygon) Binary(org.bson.types.Binary) FooBarEnum(org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTests.ClassWithMapUsingEnumAsKey.FooBarEnum) BasicDBObject(com.mongodb.BasicDBObject) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) ApplicationContext(org.springframework.context.ApplicationContext) ReadingConverter(org.springframework.data.convert.ReadingConverter) Field(org.springframework.data.mongodb.core.mapping.Field) LocalDate(org.joda.time.LocalDate) Mockito(org.mockito.Mockito) Circle(org.springframework.data.geo.Circle) ChronoUnit(java.time.temporal.ChronoUnit) PersonPojoStringId(org.springframework.data.mongodb.core.mapping.PersonPojoStringId) DBRef(com.mongodb.DBRef) ProxyFactory(org.springframework.aop.framework.ProxyFactory) ObjectId(org.bson.types.ObjectId) FieldType(org.springframework.data.mongodb.core.mapping.FieldType) DocumentTestUtils(org.springframework.data.mongodb.core.DocumentTestUtils) Document(org.springframework.data.mongodb.core.mapping.Document) Test(org.junit.jupiter.api.Test)

Example 2 with EntityProjection

use of org.springframework.data.projection.EntityProjection in project spring-data-mongodb by spring-projects.

the class MappingMongoConverterUnitTests method projectShouldReadSimpleDtoProjection.

// GH-2860
@Test
void projectShouldReadSimpleDtoProjection() {
    org.bson.Document source = new org.bson.Document("birthDate", new LocalDate(1999, 12, 1).toDate()).append("foo", "Walter");
    EntityProjectionIntrospector introspector = EntityProjectionIntrospector.create(converter.getProjectionFactory(), EntityProjectionIntrospector.ProjectionPredicate.typeHierarchy().and((target, underlyingType) -> !converter.conversions.isSimpleType(target)), mappingContext);
    EntityProjection<PersonDto, Person> projection = introspector.introspect(PersonDto.class, Person.class);
    PersonDto person = converter.project(projection, source);
    assertThat(person.getBirthDate()).isEqualTo(new LocalDate(1999, 12, 1));
    assertThat(person.getFirstname()).isEqualTo("Walter");
}
Also used : EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) BeforeEach(org.junit.jupiter.api.BeforeEach) MappingInstantiationException(org.springframework.data.mapping.model.MappingInstantiationException) EntityCallbacks(org.springframework.data.mapping.callback.EntityCallbacks) ProjectingType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.ProjectingType) CustomConversions(org.springframework.data.convert.CustomConversions) Metrics(org.springframework.data.geo.Metrics) NestedType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.NestedType) URL(java.net.URL) EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Shape(org.springframework.data.geo.Shape) AfterConvertCallback(org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback) Unwrapped(org.springframework.data.mongodb.core.mapping.Unwrapped) Disabled(org.junit.jupiter.api.Disabled) Box(org.springframework.data.geo.Box) EntityProjection(org.springframework.data.projection.EntityProjection) BasicDBList(com.mongodb.BasicDBList) Document(org.springframework.data.mongodb.core.mapping.Document) BigDecimal(java.math.BigDecimal) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DBObject(com.mongodb.DBObject) Assertions(org.assertj.core.api.Assertions) BigInteger(java.math.BigInteger) Transient(org.springframework.data.annotation.Transient) Point(org.springframework.data.geo.Point) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) TypeAlias(org.springframework.data.annotation.TypeAlias) EqualsAndHashCode(lombok.EqualsAndHashCode) ZoneId(java.time.ZoneId) Test(org.junit.jupiter.api.Test) Code(org.bson.types.Code) NonNull(org.springframework.lang.NonNull) Id(org.springframework.data.annotation.Id) java.util(java.util) WritingConverter(org.springframework.data.convert.WritingConverter) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) Getter(lombok.Getter) PersistenceConstructor(org.springframework.data.annotation.PersistenceConstructor) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Mock(org.mockito.Mock) LocalDateTime(java.time.LocalDateTime) Distance(org.springframework.data.geo.Distance) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Value(org.springframework.beans.factory.annotation.Value) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) MappingException(org.springframework.data.mapping.MappingException) Sphere(org.springframework.data.mongodb.core.geo.Sphere) Nullable(org.springframework.lang.Nullable) TextScore(org.springframework.data.mongodb.core.mapping.TextScore) Decimal128(org.bson.types.Decimal128) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) Converter(org.springframework.core.convert.converter.Converter) Polygon(org.springframework.data.geo.Polygon) Binary(org.bson.types.Binary) FooBarEnum(org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTests.ClassWithMapUsingEnumAsKey.FooBarEnum) BasicDBObject(com.mongodb.BasicDBObject) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) ApplicationContext(org.springframework.context.ApplicationContext) ReadingConverter(org.springframework.data.convert.ReadingConverter) Field(org.springframework.data.mongodb.core.mapping.Field) LocalDate(org.joda.time.LocalDate) Mockito(org.mockito.Mockito) Circle(org.springframework.data.geo.Circle) ChronoUnit(java.time.temporal.ChronoUnit) PersonPojoStringId(org.springframework.data.mongodb.core.mapping.PersonPojoStringId) DBRef(com.mongodb.DBRef) ProxyFactory(org.springframework.aop.framework.ProxyFactory) ObjectId(org.bson.types.ObjectId) FieldType(org.springframework.data.mongodb.core.mapping.FieldType) DocumentTestUtils(org.springframework.data.mongodb.core.DocumentTestUtils) LocalDate(org.joda.time.LocalDate) Test(org.junit.jupiter.api.Test)

Example 3 with EntityProjection

use of org.springframework.data.projection.EntityProjection in project spring-data-mongodb by spring-projects.

the class MappingMongoConverterUnitTests method projectShouldReadProjectionWithNestedEntity.

// GH-2860
@Test
void projectShouldReadProjectionWithNestedEntity() {
    org.bson.Document source = new org.bson.Document("addresses", Collections.singletonList(new org.bson.Document("s", "hwy")));
    EntityProjectionIntrospector introspector = EntityProjectionIntrospector.create(converter.getProjectionFactory(), EntityProjectionIntrospector.ProjectionPredicate.typeHierarchy().and((target, underlyingType) -> !converter.conversions.isSimpleType(target)), mappingContext);
    EntityProjection<ProjectionWithNestedEntity, Person> projection = introspector.introspect(ProjectionWithNestedEntity.class, Person.class);
    ProjectionWithNestedEntity person = converter.project(projection, source);
    assertThat(person.getAddresses()).extracting(Address::getStreet).hasSize(1).containsOnly("hwy");
}
Also used : EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) BeforeEach(org.junit.jupiter.api.BeforeEach) MappingInstantiationException(org.springframework.data.mapping.model.MappingInstantiationException) EntityCallbacks(org.springframework.data.mapping.callback.EntityCallbacks) ProjectingType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.ProjectingType) CustomConversions(org.springframework.data.convert.CustomConversions) Metrics(org.springframework.data.geo.Metrics) NestedType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.NestedType) URL(java.net.URL) EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Shape(org.springframework.data.geo.Shape) AfterConvertCallback(org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback) Unwrapped(org.springframework.data.mongodb.core.mapping.Unwrapped) Disabled(org.junit.jupiter.api.Disabled) Box(org.springframework.data.geo.Box) EntityProjection(org.springframework.data.projection.EntityProjection) BasicDBList(com.mongodb.BasicDBList) Document(org.springframework.data.mongodb.core.mapping.Document) BigDecimal(java.math.BigDecimal) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DBObject(com.mongodb.DBObject) Assertions(org.assertj.core.api.Assertions) BigInteger(java.math.BigInteger) Transient(org.springframework.data.annotation.Transient) Point(org.springframework.data.geo.Point) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) TypeAlias(org.springframework.data.annotation.TypeAlias) EqualsAndHashCode(lombok.EqualsAndHashCode) ZoneId(java.time.ZoneId) Test(org.junit.jupiter.api.Test) Code(org.bson.types.Code) NonNull(org.springframework.lang.NonNull) Id(org.springframework.data.annotation.Id) java.util(java.util) WritingConverter(org.springframework.data.convert.WritingConverter) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) Getter(lombok.Getter) PersistenceConstructor(org.springframework.data.annotation.PersistenceConstructor) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Mock(org.mockito.Mock) LocalDateTime(java.time.LocalDateTime) Distance(org.springframework.data.geo.Distance) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Value(org.springframework.beans.factory.annotation.Value) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) MappingException(org.springframework.data.mapping.MappingException) Sphere(org.springframework.data.mongodb.core.geo.Sphere) Nullable(org.springframework.lang.Nullable) TextScore(org.springframework.data.mongodb.core.mapping.TextScore) Decimal128(org.bson.types.Decimal128) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) Converter(org.springframework.core.convert.converter.Converter) Polygon(org.springframework.data.geo.Polygon) Binary(org.bson.types.Binary) FooBarEnum(org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTests.ClassWithMapUsingEnumAsKey.FooBarEnum) BasicDBObject(com.mongodb.BasicDBObject) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) ApplicationContext(org.springframework.context.ApplicationContext) ReadingConverter(org.springframework.data.convert.ReadingConverter) Field(org.springframework.data.mongodb.core.mapping.Field) LocalDate(org.joda.time.LocalDate) Mockito(org.mockito.Mockito) Circle(org.springframework.data.geo.Circle) ChronoUnit(java.time.temporal.ChronoUnit) PersonPojoStringId(org.springframework.data.mongodb.core.mapping.PersonPojoStringId) DBRef(com.mongodb.DBRef) ProxyFactory(org.springframework.aop.framework.ProxyFactory) ObjectId(org.bson.types.ObjectId) FieldType(org.springframework.data.mongodb.core.mapping.FieldType) DocumentTestUtils(org.springframework.data.mongodb.core.DocumentTestUtils) Document(org.springframework.data.mongodb.core.mapping.Document) Test(org.junit.jupiter.api.Test)

Example 4 with EntityProjection

use of org.springframework.data.projection.EntityProjection in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplate method findAndReplace.

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.ReactiveMongoOperations#findAndReplace(org.springframework.data.mongodb.core.query.Query, java.lang.Object, org.springframework.data.mongodb.core.FindAndReplaceOptions, java.lang.Class, java.lang.String, java.lang.Class)
	 */
@Override
public <S, T> Mono<T> findAndReplace(Query query, S replacement, FindAndReplaceOptions options, Class<S> entityType, String collectionName, Class<T> resultType) {
    Assert.notNull(query, "Query must not be null!");
    Assert.notNull(replacement, "Replacement must not be null!");
    Assert.notNull(options, "Options must not be null! Use FindAndReplaceOptions#empty() instead.");
    Assert.notNull(entityType, "Entity class must not be null!");
    Assert.notNull(collectionName, "CollectionName must not be null!");
    Assert.notNull(resultType, "ResultType must not be null! Use Object.class instead.");
    Assert.isTrue(query.getLimit() <= 1, "Query must not define a limit other than 1 ore none!");
    Assert.isTrue(query.getSkip() <= 0, "Query must not define skip.");
    MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityType);
    QueryContext queryContext = queryOperations.createQueryContext(query);
    EntityProjection<T, S> projection = operations.introspectProjection(resultType, entityType);
    Document mappedQuery = queryContext.getMappedQuery(entity);
    Document mappedFields = queryContext.getMappedFields(entity, projection);
    Document mappedSort = queryContext.getMappedSort(entity);
    return Mono.defer(() -> {
        PersistableEntityModel<S> pem = PersistableEntityModel.of(replacement, collectionName);
        maybeEmitEvent(new BeforeConvertEvent<>(pem.getSource(), pem.getCollection()));
        return maybeCallBeforeConvert(pem.getSource(), pem.getCollection()).map(pem::mutate).flatMap(it -> {
            PersistableEntityModel<S> mapped = it.addTargetDocument(operations.forEntity(it.getSource()).toMappedDocument(mongoConverter).getDocument());
            maybeEmitEvent(new BeforeSaveEvent(mapped.getSource(), mapped.getTarget(), mapped.getCollection()));
            return maybeCallBeforeSave(it.getSource(), mapped.getTarget(), mapped.getCollection()).map(potentiallyModified -> PersistableEntityModel.of(potentiallyModified, mapped.getTarget(), mapped.getCollection()));
        }).flatMap(it -> {
            Mono<T> afterFindAndReplace = doFindAndReplace(it.getCollection(), mappedQuery, mappedFields, mappedSort, 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());
            });
        });
    });
}
Also used : Document(org.bson.Document) Arrays(java.util.Arrays) BasicQuery(org.springframework.data.mongodb.core.query.BasicQuery) NumberUtils(org.springframework.util.NumberUtils) BsonUtils(org.springframework.data.mongodb.util.BsonUtils) Tuples(reactor.util.function.Tuples) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) ReactiveMongoDatabaseUtils(org.springframework.data.mongodb.ReactiveMongoDatabaseUtils) FullDocument(com.mongodb.client.model.changestream.FullDocument) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) Optionals(org.springframework.data.util.Optionals) UpdateResult(com.mongodb.client.result.UpdateResult) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) CursorOption(org.springframework.data.mongodb.core.query.Meta.CursorOption) MongoJsonSchemaMapper(org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper) AggregationOperationContext(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) ClassUtils(org.springframework.util.ClassUtils) NearQuery(org.springframework.data.mongodb.core.query.NearQuery) MappingContextEvent(org.springframework.data.mapping.context.MappingContextEvent) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) CollectionUtils(org.springframework.util.CollectionUtils) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) LogFactory(org.apache.commons.logging.LogFactory) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) ApplicationContextAware(org.springframework.context.ApplicationContextAware) Validator(org.springframework.data.mongodb.core.validation.Validator) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) MappingContext(org.springframework.data.mapping.context.MappingContext) ArrayList(java.util.ArrayList) UpdateDefinition(org.springframework.data.mongodb.core.query.UpdateDefinition) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Bson(org.bson.conversions.Bson) NoOpDbRefResolver(org.springframework.data.mongodb.core.convert.NoOpDbRefResolver) ReactiveMongoPersistentEntityIndexCreator(org.springframework.data.mongodb.core.index.ReactiveMongoPersistentEntityIndexCreator) DbRefResolver(org.springframework.data.mongodb.core.convert.DbRefResolver) MappingException(org.springframework.data.mapping.MappingException) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Nullable(org.springframework.lang.Nullable) JsonSchemaMapper(org.springframework.data.mongodb.core.convert.JsonSchemaMapper) MongoSimpleTypes(org.springframework.data.mongodb.core.mapping.MongoSimpleTypes) com.mongodb.client.model(com.mongodb.client.model) PrefixingDelegatingAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.PrefixingDelegatingAggregationOperationContext) CountContext(org.springframework.data.mongodb.core.QueryOperations.CountContext) ReactiveIndexOperations(org.springframework.data.mongodb.core.index.ReactiveIndexOperations) org.springframework.data.mongodb.core.mapping.event(org.springframework.data.mongodb.core.mapping.event) QueryMapper(org.springframework.data.mongodb.core.convert.QueryMapper) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) DeleteContext(org.springframework.data.mongodb.core.QueryOperations.DeleteContext) TypedAggregation(org.springframework.data.mongodb.core.aggregation.TypedAggregation) Mono(reactor.core.publisher.Mono) BeansException(org.springframework.beans.BeansException) MongoMappingEventPublisher(org.springframework.data.mongodb.core.index.MongoMappingEventPublisher) RelaxedTypeBasedAggregationOperationContext(org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext) ResourceUtils(org.springframework.util.ResourceUtils) Flux(reactor.core.publisher.Flux) ObjectId(org.bson.types.ObjectId) Collation(org.springframework.data.mongodb.core.query.Collation) EntityProjection(org.springframework.data.projection.EntityProjection) BsonValue(org.bson.BsonValue) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) MapReduceOptions(org.springframework.data.mongodb.core.mapreduce.MapReduceOptions) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) AdaptibleEntity(org.springframework.data.mongodb.core.EntityOperations.AdaptibleEntity) CursorType(com.mongodb.CursorType) MongoWriter(org.springframework.data.mongodb.core.convert.MongoWriter) Meta(org.springframework.data.mongodb.core.query.Meta) ReactiveEntityCallbacks(org.springframework.data.mapping.callback.ReactiveEntityCallbacks) InsertOneResult(com.mongodb.client.result.InsertOneResult) SerializationUtils(org.springframework.data.mongodb.core.query.SerializationUtils) MongoException(com.mongodb.MongoException) Collection(java.util.Collection) ApplicationListener(org.springframework.context.ApplicationListener) Collectors(java.util.stream.Collectors) PersistentEntity(org.springframework.data.mapping.PersistentEntity) List(java.util.List) Optional(java.util.Optional) UpdateMapper(org.springframework.data.mongodb.core.convert.UpdateMapper) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) 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) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) InvalidDataAccessApiUsageException(org.springframework.dao.InvalidDataAccessApiUsageException) DistinctPublisher(com.mongodb.reactivestreams.client.DistinctPublisher) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) Function(java.util.function.Function) Distance(org.springframework.data.geo.Distance) EntityReader(org.springframework.data.convert.EntityReader) ChangeStreamPublisher(com.mongodb.reactivestreams.client.ChangeStreamPublisher) ArrayFilter(org.springframework.data.mongodb.core.query.UpdateDefinition.ArrayFilter) Granularity(org.springframework.data.mongodb.core.timeseries.Granularity) MongoPersistentEntity(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) AggregationDefinition(org.springframework.data.mongodb.core.QueryOperations.AggregationDefinition) Subscriber(org.reactivestreams.Subscriber) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) Iterator(java.util.Iterator) AggregationOptions(org.springframework.data.mongodb.core.aggregation.AggregationOptions) MapReducePublisher(com.mongodb.reactivestreams.client.MapReducePublisher) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.springframework.data.mongodb.core.query.Query) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) AggregatePublisher(com.mongodb.reactivestreams.client.AggregatePublisher) ClientSessionOptions(com.mongodb.ClientSessionOptions) DeleteResult(com.mongodb.client.result.DeleteResult) Log(org.apache.commons.logging.Log) GeoResult(org.springframework.data.geo.GeoResult) SessionSynchronization(org.springframework.data.mongodb.SessionSynchronization) WriteConcern(com.mongodb.WriteConcern) Collections(java.util.Collections) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) QueryContext(org.springframework.data.mongodb.core.QueryOperations.QueryContext) DistinctQueryContext(org.springframework.data.mongodb.core.QueryOperations.DistinctQueryContext) Document(org.bson.Document) FullDocument(com.mongodb.client.model.changestream.FullDocument)

Example 5 with EntityProjection

use of org.springframework.data.projection.EntityProjection in project spring-data-mongodb by spring-projects.

the class MappingMongoConverterUnitTests method projectShouldReadSimpleInterfaceProjection.

// GH-2860
@Test
void projectShouldReadSimpleInterfaceProjection() {
    org.bson.Document source = new org.bson.Document("birthDate", new LocalDate(1999, 12, 1).toDate()).append("foo", "Walter");
    EntityProjectionIntrospector discoverer = EntityProjectionIntrospector.create(converter.getProjectionFactory(), EntityProjectionIntrospector.ProjectionPredicate.typeHierarchy().and((target, underlyingType) -> !converter.conversions.isSimpleType(target)), mappingContext);
    EntityProjection<PersonProjection, Person> projection = discoverer.introspect(PersonProjection.class, Person.class);
    PersonProjection person = converter.project(projection, source);
    assertThat(person.getBirthDate()).isEqualTo(new LocalDate(1999, 12, 1));
    assertThat(person.getFirstname()).isEqualTo("Walter");
}
Also used : EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) BeforeEach(org.junit.jupiter.api.BeforeEach) MappingInstantiationException(org.springframework.data.mapping.model.MappingInstantiationException) EntityCallbacks(org.springframework.data.mapping.callback.EntityCallbacks) ProjectingType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.ProjectingType) CustomConversions(org.springframework.data.convert.CustomConversions) Metrics(org.springframework.data.geo.Metrics) NestedType(org.springframework.data.mongodb.core.convert.DocumentAccessorUnitTests.NestedType) URL(java.net.URL) EntityProjectionIntrospector(org.springframework.data.projection.EntityProjectionIntrospector) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Shape(org.springframework.data.geo.Shape) AfterConvertCallback(org.springframework.data.mongodb.core.mapping.event.AfterConvertCallback) Unwrapped(org.springframework.data.mongodb.core.mapping.Unwrapped) Disabled(org.junit.jupiter.api.Disabled) Box(org.springframework.data.geo.Box) EntityProjection(org.springframework.data.projection.EntityProjection) BasicDBList(com.mongodb.BasicDBList) Document(org.springframework.data.mongodb.core.mapping.Document) BigDecimal(java.math.BigDecimal) ClassTypeInformation(org.springframework.data.util.ClassTypeInformation) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DBObject(com.mongodb.DBObject) Assertions(org.assertj.core.api.Assertions) BigInteger(java.math.BigInteger) Transient(org.springframework.data.annotation.Transient) Point(org.springframework.data.geo.Point) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) TypeAlias(org.springframework.data.annotation.TypeAlias) EqualsAndHashCode(lombok.EqualsAndHashCode) ZoneId(java.time.ZoneId) Test(org.junit.jupiter.api.Test) Code(org.bson.types.Code) NonNull(org.springframework.lang.NonNull) Id(org.springframework.data.annotation.Id) java.util(java.util) WritingConverter(org.springframework.data.convert.WritingConverter) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) Getter(lombok.Getter) PersistenceConstructor(org.springframework.data.annotation.PersistenceConstructor) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) Mock(org.mockito.Mock) LocalDateTime(java.time.LocalDateTime) Distance(org.springframework.data.geo.Distance) ConverterNotFoundException(org.springframework.core.convert.ConverterNotFoundException) Value(org.springframework.beans.factory.annotation.Value) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) MappingException(org.springframework.data.mapping.MappingException) Sphere(org.springframework.data.mongodb.core.geo.Sphere) Nullable(org.springframework.lang.Nullable) TextScore(org.springframework.data.mongodb.core.mapping.TextScore) Decimal128(org.bson.types.Decimal128) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) Converter(org.springframework.core.convert.converter.Converter) Polygon(org.springframework.data.geo.Polygon) Binary(org.bson.types.Binary) FooBarEnum(org.springframework.data.mongodb.core.convert.MappingMongoConverterUnitTests.ClassWithMapUsingEnumAsKey.FooBarEnum) BasicDBObject(com.mongodb.BasicDBObject) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) ApplicationContext(org.springframework.context.ApplicationContext) ReadingConverter(org.springframework.data.convert.ReadingConverter) Field(org.springframework.data.mongodb.core.mapping.Field) LocalDate(org.joda.time.LocalDate) Mockito(org.mockito.Mockito) Circle(org.springframework.data.geo.Circle) ChronoUnit(java.time.temporal.ChronoUnit) PersonPojoStringId(org.springframework.data.mongodb.core.mapping.PersonPojoStringId) DBRef(com.mongodb.DBRef) ProxyFactory(org.springframework.aop.framework.ProxyFactory) ObjectId(org.bson.types.ObjectId) FieldType(org.springframework.data.mongodb.core.mapping.FieldType) DocumentTestUtils(org.springframework.data.mongodb.core.DocumentTestUtils) LocalDate(org.joda.time.LocalDate) Test(org.junit.jupiter.api.Test)

Aggregations

ObjectId (org.bson.types.ObjectId)5 ApplicationContext (org.springframework.context.ApplicationContext)5 BasicDBList (com.mongodb.BasicDBList)4 BasicDBObject (com.mongodb.BasicDBObject)4 DBObject (com.mongodb.DBObject)4 DBRef (com.mongodb.DBRef)4 BigDecimal (java.math.BigDecimal)4 BigInteger (java.math.BigInteger)4 URL (java.net.URL)4 LocalDateTime (java.time.LocalDateTime)4 ZoneId (java.time.ZoneId)4 ChronoUnit (java.time.temporal.ChronoUnit)4 java.util (java.util)4 EqualsAndHashCode (lombok.EqualsAndHashCode)3 Getter (lombok.Getter)3 RequiredArgsConstructor (lombok.RequiredArgsConstructor)3 Assertions (org.assertj.core.api.Assertions)3 Binary (org.bson.types.Binary)3 Code (org.bson.types.Code)3 Decimal128 (org.bson.types.Decimal128)3