【问题标题】:Mongo @DBRef uniqueMongodb @DBRef 唯一
【发布时间】:2015-06-10 14:15:24
【问题描述】:

我的应用程序使用 Spring Boot / JPA / MongoDB。

我使用

将我的域类映射到 MongoDB
org.springframework.data.mongodb.core.mapping.Document;
org.springframework.data.mongodb.core.index.Indexed;
org.springframework.data.mongodb.core.mapping.DBRef;

一切都很好,除非尝试使 DBRef 独一无二:

@DBRef @Indexed(unique = true)
private User owner;

我尝试了@DBRef、@Indexed (unique=true) 的不同组合,但无法使 DBRef 独一无二。我可以使其他字段类型唯一,例如以下示例中的“名称”

@Indexed(unique = true)
@Size(min = 2, max = 100)
@Column(length = 100)
private String name;

但找不到如何使我的 DBRef 字段唯一。

【问题讨论】:

  • 出于兴趣:索引在数据库级别上的外观如何(colleciton.getIndexes()
  • @xeraa - 请参阅下面的代码。我用 smeCode 替换了名称不佳的“名称”字段。 DBRef 所有者是有问题的变量。我使用了 db.NT_SMES.getIndexes(),所有者没有被索引。 smeCode 和 _id 被列为索引。 (抱歉没有发布代码 - 我无法正确格式化评论)

标签: spring mongodb spring-data spring-data-mongodb


【解决方案1】:

我来自 Morphia 的映射方面,但我会试试这个:

@CompoundIndexes({
    @CompoundIndex(name = "owner", def = "{'owner.id' : 1}", unique = true)
})

【讨论】:

  • 谢谢@xeraa。复合索引不是我想要的。我想将 DBRef 变量标记为唯一的。
  • 你试过了吗?这应该朝着正确的方向发展:stackoverflow.com/a/15819034/573153 由于您不想索引所有者而是所有者的 ID,因此您需要一些解决方法。因此,您需要某种类级别关联,因为属性上的关联没有达到它
  • @xeraa我确实尝试过,并在不同的地方放置了“独特”。仍然无法让“所有者”独一无二。我将根据您的链接检查 MongoTemplate 文档。非常感谢
猜你喜欢
  • 2012-02-01
  • 1970-01-01
  • 2015-10-21
  • 2012-11-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
相关资源
最近更新 更多