Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoRepository save causing Duplicate Key error

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("[email protected]");
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?

like image 317
conquester Avatar asked Mar 06 '23 07:03

conquester


2 Answers

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
}
like image 57
conquester Avatar answered Apr 07 '23 13:04

conquester


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.

like image 21
dhrubo Avatar answered Apr 07 '23 12:04

dhrubo