From 1edbdcb38358363e6d82a1c4f185b7835a6d3139 Mon Sep 17 00:00:00 2001 From: Christoph Strobl Date: Thu, 16 Jan 2025 08:20:41 +0100 Subject: [PATCH] Fix reading back id field value when multiple id property candidates exist. We now check if a property identifies as the entities id property when populating values read from the source document. Original pull request: #4878 Closes #4877 --- .../core/convert/MappingMongoConverter.java | 2 +- .../MappingMongoConverterUnitTests.java | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) 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 35b1d77792..7955cb2f9b 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 @@ -134,7 +134,7 @@ public class MappingMongoConverter extends AbstractMongoConverter private static final BiPredicate, MongoPersistentProperty> PROPERTY_FILTER = (e, property) -> { - if (property.isIdProperty()) { + if (e.isIdProperty(property)) { return false; } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java index 2536d28291..f44e094705 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/MappingMongoConverterUnitTests.java @@ -3313,6 +3313,21 @@ void projectShouldReadComplexIdType(Class projectionTargetType) { .extracting("id").isEqualTo(idValue); } + @Test // GH-4877 + void shouldReadNonIdFieldCalledIdFromSource() { + + WithRenamedIdPropertyAndAnotherPropertyNamedId source = new WithRenamedIdPropertyAndAnotherPropertyNamedId(); + source.abc = "actual-id-value"; + source.id = "just-a-field"; + + org.bson.Document document = write(source); + assertThat(document).containsEntry("_id", source.abc).containsEntry("id", source.id); + + WithRenamedIdPropertyAndAnotherPropertyNamedId target = converter.read(WithRenamedIdPropertyAndAnotherPropertyNamedId.class, document); + assertThat(target.abc).isEqualTo(source.abc); + assertThat(target.id).isEqualTo(source.id); + } + org.bson.Document write(Object source) { org.bson.Document target = new org.bson.Document(); @@ -4531,4 +4546,10 @@ public DoubleHolderDto(DoubleHolder number) { } } + static class WithRenamedIdPropertyAndAnotherPropertyNamedId { + + @Id String abc; + String id; + } + }