Spring Data MongoRepository 保存导致重复键错误

con*_*ter 4 spring-data spring-mongo spring-boot

这是实体:

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

我使用他们的电子邮件获取该用户,然后更改他们的姓名。我使用ApplicationUserRepository的自动装配实例。

ApplicationUser applicationUser = applicationUserRepository.findByEmail("abc@gmail.com");
applicationUser.setName("John Doe 2");
Run Code Online (Sandbox Code Playgroud)

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

applicationUserRepository.save(applicationUser);
Run Code Online (Sandbox Code Playgroud)

我在现场电子邮件中收到重复的密钥错误。为什么会这样?据我从文档中获得,如果 ObjectId 相同,save方法会更新同一个文档。既然我没有更改 objectId 那么为什么它在保存期间尝试创建一个新的 ApplicationUser ?

con*_*ter 5

我得到了解决方案。创建实体时,我必须明确声明 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
}
Run Code Online (Sandbox Code Playgroud)