Spring Boot中的MongoDB索引(unique=true)无效。

9

我有如下类作为我的文档。

@Data
@Builder
@Document(collection = "test")
public class TestData {
    @Id
    private String id;

    private String name;

    @Indexed(unique = true)
    private String hash;

}

即使我启用了唯一性索引,但我仍然可以向集合中插入重复的文档。但是如果我在Mongo shell中生成索引,则可以正常工作。
是否有任何方法可以只通过代码指定唯一索引?

@Indexed 不能应用于类级别,它应该应用于字段级别。请使用 @CompoundIndex 代替。 - Amit kumar
@Amitkumar:我也尝试过使用@CompoundIndex(def = "{ 'hash': 1 }", unique = true),但它并没有起作用。 - Sumedha
@Amitkumar:这是语法错误,不能那样做。 - Sumedha
1
请查看此重复问题 - spring.data.mongodb.auto-index-creation=true 属性更改对我有用 https://dev59.com/vlQJ5IYBdhLWcg3w05f2 - Manish Patel
这个回答解决了你的问题吗?Spring Boot / Mongo使用索引注释不会创建索引 - Manish Patel
显示剩余4条评论
3个回答

3
这是我的代码中如何使用复合索引。
@Getter
@Setter
@Document
@CompoundIndexes({
@CompoundIndex(name = "name_author_idx", def = "{'name' : 1, 'author' : 1}", unique = true, background = true)})
public class Book implements Transformer {

    @Id
    private String id;

    @Field(name = "name")
    private String name;

    @Field(name = "author")
    private String author;

    @Field(name = "qty")
    private Integer qty;

    @Field(name = "price")
    private Double price;

    @Field(name = "created_time")
    private LocalDateTime createdTime = LocalDateTime.now();
}

3
请在Spring Boot应用程序的application.properties文件中使用以下代码,它将起作用。 spring.data.mongodb.auto-index-creation: true 谢谢。

1
如果你有一个配置组件,你应该像这样覆盖autoIndexCreation方法:
@Configuration
public class MongoConfiguration extends AbstractMongoClientConfiguration 
{
@Override
protected boolean autoIndexCreation() {
return true;
}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接