Spring Data MongoRepository save causing Duplicate

2019-08-31 05:11发布

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?

2条回答
干净又极端
2楼-- · 2019-08-31 05:32

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-31 05:53

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
}
查看更多
登录 后发表回答