gpt4 book ai didi

java - Spring 数据蒙戈 : How to save batch ignoring all duplicate key errors?

转载 作者:可可西里 更新时间:2023-11-01 09:26:03 24 4
gpt4 key购买 nike

我有以下域对象:

@Document
class Foo {
@Id
private final String bar;
private final String baz;
// getters, setters, constructor omitted
}

插入如下:

Collection<Foo> foos = ...;
mongoTemplate.insert(foos, Foo.class);

如何在忽略所有重复键异常的情况下在一次调用中保存所有结果?

最佳答案

在我的例子中,像@marknorkin 的回答那样允许修改/覆盖现有文档是不合适的。相反,我只想插入 文档。我使用 MongoOperations 想到了这个,它在 Spring 中是可注入(inject)的。下面的代码是在 Kotlin 中。

 try {
// we do not want to overwrite existing documents, especially not behind the event horizon
// we hence use unordered inserts and supresss the duplicate key exceptions
// as described in: https://docs.mongodb.com/v3.2/reference/method/db.collection.insertMany/#unordered-inserts
mongoOps.bulkOps(BulkOperations.BulkMode.UNORDERED, EventContainer::class.java)
.insert(filtered)
.execute()
} catch (ex: BulkOperationException) {
if (!isDuplicateKeyException(ex)) {
throw ex
}
}

有了这个小 helper

private fun isDuplicateKeyException(ex: BulkOperationException): Boolean {
val duplicateKeyErrorCode = 11000
return ex.errors.all { it.code == duplicateKeyErrorCode }
}

关于java - Spring 数据蒙戈 : How to save batch ignoring all duplicate key errors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com