MongoRepository保存导致重复密钥错误

MongoRepository保存导致重复密钥错误

本文介绍了Spring Data MongoRepository保存导致重复密钥错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是实体:

@Document
@Data
public class ApplicationUser {
    private String name;
    @Indexed(unique = true)
    private String email;
    private String organization = null;
    // other fields
}

我使用他们的电子邮件获取了该用户,然后更改了他们的名字.我使用ApplicationUserRepository的 autowired 实例.

I fetch this user using their email and then change their name. I use the autowired instance of ApplicationUserRepository.

ApplicationUser applicationUser = applicationUserRepository.findByEmail("[email protected]");
applicationUser.setName("John Doe 2");

然后,我尝试再次在数据库中更新此实体:

Then I try to update this entity again in the database:

applicationUserRepository.save(applicationUser);

我在现场电子邮件中收到重复的密钥错误.为什么会这样呢?据我从文档获得的信息,如果ObjectId相同,则 save 方法会更新同一文档.由于我没有更改objectId,所以为什么在保存过程中尝试创建一个新的ApplicationUser?

I get a duplicate key error on the field email. Why is this happening?As far as I get from the documentation, the save method updates the same document if the ObjectId is the same. Since I haven't changed the objectId then why is it trying to create a new ApplicationUser during saving?

推荐答案

我找到了解决方案.创建实体时,我必须明确声明ID.

I got the solution.When creating the entity, I have to explicitly declare the Id.

这是实体:

@Document
@Data
public class ApplicationUser {
    @Id
    private ObjectId _id;
    private String name;
    @Indexed(unique = true)
    private String email;
    private String organization = null;
    // other fields
}

这篇关于Spring Data MongoRepository保存导致重复密钥错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:03