Skip to content

Commit 37f2d39

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 0e481b2 commit 37f2d39

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
@@ -1414,7 +1414,10 @@ protected <T> Collection<T> doInsertBatch(String collectionName, Collection<? ex
14141414
maybeEmitEvent(new BeforeSaveEvent<>(initialized, document, collectionName));
14151415
initialized = maybeCallBeforeSave(initialized, document, collectionName);
14161416

1417-
documentList.add(document);
1417+
MappedDocument mappedDocument = queryOperations.createInsertContext(MappedDocument.of(document))
1418+
.prepareId(uninitialized.getClass());
1419+
1420+
documentList.add(mappedDocument.getDocument());
14181421
initializedBatchToSave.add(initialized);
14191422
}
14201423

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;
@@ -3109,6 +3110,18 @@ public void generatesIdForInsertAll() {
31093110
assertThat(jesse.getId()).isNotNull();
31103111
}
31113112

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

0 commit comments

Comments
 (0)