Skip to content

Commit 6c4d490

Browse files
christophstroblmp911de
authored andcommitted
Fix @MongoId mapping for insertAll.
This commit fixes an issue where id properties annotated with MongoId had not been converted into the desired target type when inserting a collection of objects instead a single one. Resolves: #4944 Original pull request: #4945
1 parent fc5e092 commit 6c4d490

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

Diff for: spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -1433,7 +1433,10 @@ protected <T> Collection<T> doInsertBatch(String collectionName, Collection<? ex
14331433
maybeEmitEvent(new BeforeSaveEvent<>(initialized, document, collectionName));
14341434
initialized = maybeCallBeforeSave(initialized, document, collectionName);
14351435

1436-
documentList.add(document);
1436+
MappedDocument mappedDocument = queryOperations.createInsertContext(MappedDocument.of(document))
1437+
.prepareId(uninitialized.getClass());
1438+
1439+
documentList.add(mappedDocument.getDocument());
14371440
initializedBatchToSave.add(initialized);
14381441
}
14391442

Diff for: spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java

+13
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import java.util.stream.IntStream;
3535
import java.util.stream.Stream;
3636

37+
import org.bson.Document;
3738
import org.bson.types.ObjectId;
3839
import org.junit.jupiter.api.AfterEach;
3940
import org.junit.jupiter.api.Test;
@@ -3110,6 +3111,18 @@ public void generatesIdForInsertAll() {
31103111
assertThat(jesse.getId()).isNotNull();
31113112
}
31123113

3114+
@Test // GH-4944
3115+
public void insertAllShouldConvertIdToTargetTypeBeforeSave() {
3116+
3117+
RawStringId walter = new RawStringId();
3118+
walter.value = "walter";
3119+
3120+
RawStringId returned = template.insertAll(List.of(walter)).iterator().next();
3121+
org.bson.Document document = template.execute(RawStringId.class, collection -> collection.find().first());
3122+
3123+
assertThat(returned.id).isEqualTo(document.get("_id"));
3124+
}
3125+
31133126
@Test // DATAMONGO-1208
31143127
public void takesSortIntoAccountWhenStreaming() {
31153128

0 commit comments

Comments
 (0)