我无法执行更新操作。在 mongodb 3.4 中使用 spring boot。 在尝试保存时,我收到以下类型的错误:
WriteError{code=11000, message='E11000 duplicate key error collection
我的域类正在扩展另一个基础域类。我目前的发现是基域类包含用@Version 注释的“私有(private)长版本”。我的猜测是这是导致问题的领域。 到目前为止我尝试过的事情:
- 初始化“private Long version = 0L;”我的文档只更新一次,进一步更新会出现以下错误:
Something went wrong in service layer while updating the Employee.Cannot save entity 119794669940 with version 1 to collection Employee. Has it been modified meanwhile?
- 删除@Version 后数据更新得很好。 (不是解决方案,因为需要版本)
- 查看了 E11000 duplicate key error when doing PUT for modifiable resource with Spring Data Rest并尝试在版本字段上使用@JsonIgnore。它也抛出相同的重复键错误:
WriteError{code=11000, message='E11000 duplicate key error collection.
一些附加信息:
- 到目前为止,在我尝试过的任何上述情况下,我都没有在 put 正文中发送版本(使用版本 key 发送它们会产生相同的错误。
有人知道发生了什么或如何进一步进行吗?
最佳答案
如果您尝试使用 null
或 0
(对于原语)来持久化一个实体,它会被视为一个新实体。
如果版本是任何其他版本,则将其视为更新,并检查该版本是否为数据库中存在的版本以进行乐观锁定。
因此您需要设置版本。 要么将其包含在请求的正文中,要么尝试从数据库加载实体并使用其中的版本(如果找到任何实体)。 当然,后一个版本在某种程度上打败了乐观锁定的想法。
另见 answer about the handling of the version attribute if you are using Spring Data Rest
关于java - 无法在 Spring 引导中更新文档。在 mongorepository.save 上获取 E11000 重复键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71347771/