Working with MongoDB, I decided username
should be unique. Okay, I use @Indexed(unique = true)
(application runs fine), but @Indexed(unique = true)
isn't working. I can still add 2 users with the same username.
Source (Spring Data: Unique field in MongoDB document) tells me to put spring.data.mongodb.auto-index-creation=true
in my application.properties
. (also tried putting it in application.yml, gave same error)
Later I also realized the @Size
annotation from the jakarta.validation-api
doesn't work.
User model:
import org.bson.types.Binary;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import java.util.List;
@Document(collection = "users")
public class User {
@Id
private String id;
private Binary profilePicture;
private String bio;
@Size(max = 20)
@Indexed(unique = true)
private String username;
private String password;
private List<Integer> kweets;
private List<User> followers;
private List<User> following;
}
Repository (is just standard):
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
</dependencies>
Id
's do get auto-generated though, which means @Id
does work.
Where could the problem lay, at first I thought it was just @Indexed
, but turns out @Size
doesn't work either.