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

Most upvoted comments

I have solved adding the option spring.data.mongodb.auto-index-creation: true in the application.yml configuration file

Just an observation for other people: I just ran into this problem and setting the auto-index-creation property to true didn’t fix it. The reason was cause i’m using a custom Mongo configuration where i extend AbstractMongoClientConfiguration, so i had to add this to the config class:

@Override
public boolean autoIndexCreation() {
    return true;
}

Now the index is working ;p

I haven’t found a workaround yet 😕 On Sun, Dec 6, 2020 at 7:19 PM ClimberBear @.***> wrote: I have this issue too. It is open from August. Any suggestion? Did it work in previous versions? — You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub <#320 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABN3EEY44WUOSIXVESUUVLTSTPKMZANCNFSM4PVOMFKA .

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)