5

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?

2
  • 1
    For me the issue was related to the entity's @Version field. When I forgot to set it for an update I received the DuplicateKey exception. After copying it correctly from the old version of the entity, it worked. Commented Dec 23, 2022 at 10:54
  • Marvin, thanks for the great answer! I think you should add it also as an answer, because it can be missed in comments. This helped me a lot, and it is VERY not obvious to understand that this is the reason when the error you get is "duplicate key". Commented May 22, 2023 at 15:11

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

you saved my day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.