Spring Data MongoRepository 保存导致重复键错误 [英] Spring Data MongoRepository save causing Duplicate Key error

查看:47
本文介绍了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("abc@gmail.com");
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 保存导致重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆