de.flapdoodle.embed.mongo: @Indexed(unique=true) does not cause Dupe Key error
When you mark a field as unique, insertion of a new document with the same value in that field should throw a duplicate key error. I can currently insert 2 documents with duplicate values via spring boot.
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
</parent>
    ....
<dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
</dependency>
Create a user class:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "appUsers")
public class User {
    @Id
    private String id;
    @Indexed(unique = true) 
    private String userName;
    @Indexed(unique = true)
    private String email;
In a test I can insert twice:
User user1 = new User("foobar","foo@bar.com"); // userName and email address in constructor
User user2 = new User("foobar","foo@bar.com"); 
userRepository.insert(user1);
userRepository.insert(user2); // expect an error here
userRepository is Autowired is a standard mongo repository:
public interface UserRepository extends MongoRepository<User,String> 
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 2
- Comments: 15
I have solved adding the option
spring.data.mongodb.auto-index-creation: truein the application.yml configuration fileJust an observation for other people: I just ran into this problem and setting the
auto-index-creationproperty to true didn’t fix it. The reason was cause i’m using a custom Mongo configuration where i extendAbstractMongoClientConfiguration, so i had to add this to the config class:Now the index is working ;p
Thanks for keep trying!!! My question is because I’m following the examples in the the book “Hands-On Microservices with Spring Boot and Spring Cloud” by Magnus Larson, and he uses this sample. So, it worked sometime ago! (or he is tricking his own book)