【问题标题】:Spring Data: Unique field in MongoDB documentSpring Data:MongoDB文档中的唯一字段
【发布时间】:2018-08-29 07:42:51
【问题描述】:

假设我有以下数据库实体:

@Document(collection = "users")
public class User {

    @Id
    private String id;

    private String firstname;

    private String lastname;

    private String email; 

}

如何强制字段电子邮件是唯一的?这意味着 MongoDB 应该在应用程序尝试保存实体时检查是否已经存在使用此电子邮件地址的用户记录。

问候, 史蒂芬

【问题讨论】:

  • @Indexed(unique = true)
  • 所以它只能与@Indexed 结合使用?

标签: java spring mongodb spring-data


【解决方案1】:

Mongodb 需要创建并索引一个字段,才能知道该字段是否唯一。

@Indexed(unique=true)
private String email;

【讨论】:

  • 我试过了,mongo 驱动程序没有做任何强制使这个独一无二
  • @David:你是否也在 mongo 端创建了索引?
【解决方案2】:

首先,在模型中的字段上方使用Indexed 注释,如下所示:

@Indexed(unique = true)
private String email;

此外,您应该以编程方式定义您的索引。定义 MongoTemplate 时应使用以下代码。

mongoTemplate.indexOps("YOUR_COLLECTION_NAME").ensureIndex(new Index("YOUR_FEILD_OF_COLLECTION", Direction.ASC).unique());

对于您的情况,您应该使用:

mongoTemplate.indexOps("users").ensureIndex(new Index("email", Direction.ASC).unique());

【讨论】:

  • 如果所有工作都在mongoTemplate上完成,为什么还要使用注解?
【解决方案3】:

这对我有用,但你必须删除你的数据库,然后重新运行你的应用程序

 spring.data.mongodb.auto-index-creation=true

【讨论】:

    【解决方案4】:

    从 Spring Data MongoDB 3.0 开始,自动索引创建默认关闭。所以基本上,除了使用@Indexed,您还必须配置默认索引选项。您需要做的是在application.properties 文件中创建spring.data.mongodb.auto-index-creation=true,然后@Indexed 将像魅力一样工作!

    【讨论】:

      【解决方案5】:

      您可以尝试以下解决方案之一,它对我有用。

      注意:请在使用以下解决方案重试之前删除您的数据库。

      解决方案 - 1

      @Indexed(unique = true, background = true)
      private String emailId;
      

      解决方案 - 2

      spring.data.mongodb.auto-index-creation=true 添加到您的 application.properties 文件中。

      spring.data.mongodb.auto-index-creation:true 添加到您的 yaml 文件中

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 2020-09-08
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        • 2022-01-24
        相关资源
        最近更新 更多