Spring Data MongoRepository save causing Duplicate Key error

若如初见. 提交于 2020-01-06 06:49:09

问题


Here is the Entity:

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

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);

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?


回答1:


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

Here is the Entity:

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



回答2:


I had similar issue where I was retrieving by id and then trying to update the retrieved POJO and then save it back with MongoRepository.save() call. It was on MongoDB 4.x with Spring Boot 2.1.0. I added the @Transactional annotation to my service method and everything worked like a charm. The duplicate key exception on id field was resolved.



来源:https://stackoverflow.com/questions/50153457/spring-data-mongorepository-save-causing-duplicate-key-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!